(function(){
    var synxis = {
	flash: function() {
	    $("body.home div#masthead").flash({
		src:"/flash/masthead-home.swf",
		 width:750,
		 height:229,
		 wmode:"transparent",
		 quality:"high"},
	     {version:"8"});

	    $('div#global-map').flash({
		src:'/flash/global_map.swf',
		width:684,
		height:445,
		wmode:'transparent',
		quality:'high'
	    }, {version:'8'},
		function(htmlOptions) {
		    var customerMap = location.href.indexOf('customer-map.php')!=-1,
			globalMap = location.href.indexOf('global-office-map.php')!=-1;
		    htmlOptions.flashvars['section'] = window.globals['section'] ? window.globals['section'] : customerMap ? 'worldwide' : 'global';
		    $(this).html($.fn.flash.transform(htmlOptions));
		}
	    );
        
        $('div#synxis-gallery').flash({
        src:'/flash/synxis-gallery.swf',
        width:650,
        height:440,
        wmode:'transparent',
        quality:'high'
        }, {version:'8'},
        function(htmlOptions) {
            htmlOptions.flashvars.configXML = '/flash/xml/images.xml';
            $(this).html($.fn.flash.transform(htmlOptions));
        }
        );

	    $('div#sales-consultation').flash({
		src:'/flash/sales_consultation.swf',
		width:684,
		height:445,
		wmode:'transparent',
		quality:'high'
	    }, {version:'8'});
        
        $('div#partner-logo-rotation').flash({
        src:'/flash/logo_bar.swf',
        width:744,
        height:80,
        wmode:'transparent',
        quality:'high'
        }, {version:'8'});
	}, // synxis.flash

	sifr: function() {
	    $('ul.vertical-list h3').sifr({ strSWF: '/flash/sifr/myriad-pro.swf', strColor:'#3d3a2b', strLinkColor: '#3d3a2b', strHoverColor: '#3d3a2b', strWmode: 'transparent', intPadding: [0,0,0,0] }, {expressInstall:true}
	    ); 
	}, // synxis.sifr

	expandCollapseNews: function() {
	    var current = $('#news-events h2.current');

	    var news = $('h2#news a'), events = $('h2#events a'), newsListings = $('#news-listings'), eventListings = $('#event-listings'),
	    newsLink = $('#view-news'), eventsLink = $('#view-events');

	    eventsLink.hide();
	    news.click(function() {
		events.parent().removeClass('current');
		$(this).parent().addClass('current');

		newsListings.fadeIn('slow');
		eventListings.hide();
		newsLink.fadeIn('slow');
		eventsLink.hide();

		return false;
	    });

	    events.click(function() {
		news.parent().removeClass('current');
		$(this).parent().addClass('current');

		eventListings.fadeIn('slow');
		newsListings.hide();
		eventsLink.fadeIn('slow');
		newsLink.hide();

		return false;
	    });
	}, // synxis.expandCollapseNews

	clientLogin:function() {
	    var clientLoginForm = $('#client-login');
	    var targetUrl = $('select#login');

	    clientLoginForm.attr('action', targetUrl.val());
	    targetUrl.change(function() {
		clientLoginForm.attr('action', $(this).val());
	    });
	}, // synxis.clientLogin

	eventsCalendar:function() {
		var months = {
		    january:1, february:2, march:3, april:4,
		    may:5, june:6, july:7, august:8, september:9, 
		    october:10, november:11, december:12
		    },
		    filters = { 247:'attending', 292:'exhibit', 293:'speaking' },
		    elemPreviousLink = $( 'a#previous-anchor' ),
		    elemNextLink = $( 'a#next-anchor' ),
		    elemMonthsDropdown = $( '#select_month' )[0],
		    elemFilterDropdown = $( '#filter_by' )[0],
		    elemFirstMonth = $( elemMonthsDropdown ).find( 'option:first' )[0],
		    elemLastMonth = $( elemMonthsDropdown ).find( 'option:last' )[0],
		    elemSecondToLastMonth = $( elemLastMonth ).prev()[0],
		    elemThirdToLastMonth = $( elemLastMonth ).prev().prev()[0],
		    thirdToLastClicked=false,
                    activeMonths=[],
		    elemVisibleCalendars,
		    initialState=true,
		    lastState=false,
		    grabbingData=false,
		    toggleDone=false,
		    filterString,

		    updateNextPrevious = function() {

			$(elemNextLink).unbind();
			$(elemPreviousLink).unbind();

			// register the event handlers to be used for next/previous buttons.
			if ( !lastState ) { 
			    elemNextLink.click( function() { 
				if ( !grabbingData ) { grabMonth('next',1); }
				return false; 
			    }) 
			}
			if ( !initialState ) { 
			    elemPreviousLink.click( function() { 
				if ( !grabbingData ) { grabMonth('previous',1); }
				return false; 
			    }); 
			}

			if ( initialState ) { 
			    $( elemPreviousLink ).hide();
			} else { 
			    $( elemPreviousLink ).show();
			}

			if ( lastState ) { 
			    $( elemNextLink ).hide();
			} else { 
			    $( elemNextLink ).show();
			}
                },
		    updateMonthInfo = function( filter ) {

			elemVisibleCalendars = $( 'div#calendars div.calendar:visible' );
			if ( elemVisibleCalendars.length !== 3 ) {
			    log('the num of visible calendars is NOT 3.');
			    return false;
			}
			var lastActive;

			elemVisibleCalendars.each( function( i, obj ) {
			    var monthString = $( '.month-name', obj ).text() + ' ' +  $( '.month-year', obj ).text();
			    monthString = monthString.replace(/[ ]{2}/, ' ');

			    var optionElem = $( 'option[@text="' + monthString + '"]', elemMonthsDropdown )[0];

			    if ( !optionElem.exists ) {
				attachEventPopups( obj );
			    }

			    if ( filter ) {
				attachEventPopups( obj );
			    }

			    optionElem.active = true;
			    optionElem.exists = true;
			    optionElem.reference = obj;
			    optionElem.monthString = monthString;

                            activeMonths[i] = optionElem;


			    switch ( i ) {
				case 0:
				    if ( !optionElem.first ) {
					initialState = false;
				    } else { initialState = true; }
				    $( elemMonthsDropdown ).find('option[@text=' + monthString + ']')[0].selected=true; 
				break;

				case 2:
				    if ( !optionElem.last ) {
                                        lastState = false;
					nextThirdMonth = $( optionElem ).next()[0];
                                    } else { 
					lastState = true; 
				    }
				break;
			    }
			    
			});

                        $( activeMonths ).each(function( i, obj) {
                            var optionElem = obj;
                            var next = $(optionElem).next();
                            var prev = $(optionElem).prev();
                            
                            optionElem.nextMonthExists = next.length ? next[0].exists : false;
                            optionElem.prevMonthExists = prev.length ? prev[0].exists : false;

                        })
			updateNextPrevious();
		    };
		// end of initial assignments

		// assign the first and last month option properties
		elemFirstMonth.first = true;
		elemLastMonth.last = true;

		window.second = elemSecondToLastMonth;
		window.first = elemLastMonth;

		updateMonthInfo();
		attachListingPopups();

		function filterByType( type, filterString ) {
		    grabMonth( null, 3, type, filterString );
		}

		$( elemFilterDropdown.form ).submit( function() {
		    filterString = $( elemMonthsDropdown ).find('option[@value=' + $( elemMonthsDropdown ).val() + ']').text();
		    var filterType = elemFilterDropdown.value;
		    var option = $( elemMonthsDropdown ).find('option[@text=' + filterString + ']')[0];
		    if( !filterType && filterString == $(activeMonths[0]).text() ) {
		    }
		    if ( option == elemLastMonth ) {
			filterString = $( elemMonthsDropdown ).find('option[@value=' + $( elemMonthsDropdown ).val() + ']').prev().prev().text();
			log( filterString );
		    } else if ( option == elemSecondToLastMonth ) {
			filterString = $( elemMonthsDropdown ).find('option[@value=' + $( elemMonthsDropdown ).val() + ']').prev().text();
			log( filterString );
		    } else {
		    }

		    filterByType ( filterType, filterString );
		    return false;
		});


		function grabMonth( str, howMany, filter, filterMonth ) {
		    var next = ( str == 'next' ) ? 1 : 0,
			prev = ( str == 'previous' ) ? 1 : 0,
			isFilter = ( str === null ) ? 1 : 0,
			dateString = 'numberofmonths=' + howMany,
                        doXHR = false, 
			exists = false,
			hitPrev=false;

                    if ( next && !activeMonths[2].nextMonthExists ) {
			dateString+= '&month=' +  ( $(activeMonths[2]).next().val() ) + '&year=' + ( $(activeMonths[2]).next().text().slice(-4) );
                        doXHR = true;
			    thirdToLastClicked = false;
		    } else if ( next && activeMonths[2].nextMonthExists ) {
			dateString+= '&month=' +  ( $(activeMonths[2]).next().val() ) + '&year=' + ( $(activeMonths[2]).next().text().slice(-4) );
			exists = true;
			    thirdToLastClicked = false;
                    } else if ( prev && !activeMonths[0].prevMonthExists ) {
			log('prev month does not exist');

			if ( activeMonths[1] == elemSecondToLastMonth ) {
			    log('second2last');
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
			    log( 'dstr' + dateString );
			    hitPrev = true;
			} else if ( activeMonths[1] == elemLastMonth ) {
			    log('last');
			    hitPrev = true;
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().prev().text().slice(-4) );
			    log( 'dstr' + dateString );
			} 
			else if ( activeMonths[1] == elemThirdToLastMonth ) {
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
			    hitPrev=true;
			    thirdToLastClicked=true;
			    
			}
			else {
			    log('else');
			    if ( thirdToLastClicked ) {
				dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
				thirdToLastClicked = false;
				hitPrev = true;
			    } else {
				hitPrev = true;
				dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
			    }
			    log( 'dstr' + dateString );
			}
                        doXHR = true;
                    } else if ( prev && activeMonths[0].prevMonthExists ) {
			log('prev month exists');
			if ( activeMonths[1] == elemSecondToLastMonth ) {
			    log('second2last');
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
			    log( 'dstr' + dateString );
			    hitPrev = true;
			} else if ( activeMonths[1] == elemLastMonth ) {
			    log('last');
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().prev().text().slice(-4) );
			    log( 'dstr' + dateString );
			    hitPrev = true;
			}
			else if ( activeMonths[1] == elemThirdToLastMonth ) {
			    dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
			    thirdToLastClicked=true;
			    hitPrev = true;

			} else {
			    log('else');
			    if ( thirdToLastClicked ) {
				dateString+= '&month=' + ( $(activeMonths[1]).prev().prev().val() ) + '&year=' + ( $(activeMonths[1]).prev().prev().text().slice(-4) );
				if ( activeMonths[0] == elemMonthsDropdown[ elemMonthsDropdown.length-5 ] ) {
				    dateString+= '&month=' + ( $(activeMonths[1]).val() ) + '&year=' + ( $(activeMonths[1]).text().slice(-4) );
				    thirdToLastClicked = false;
				}
			    } else {
				dateString+= '&month=' + ( $(activeMonths[1]).val() ) + '&year=' + ( $(activeMonths[1]).text().slice(-4) );
			    }
			}
			exists = true;
                    } else {
			var filterArr = filterMonth.split(' ');
			if ( filterArr.length !== 2 ) {
			    log('filter string error.');
			}
			dateString+= '&month=' + months[filterArr[0].toLowerCase()] + '&year=' + filterArr[1] + '&fid=' + filter;
			doXHR = true;
		    }

		    function callback( data ) {

                        if ( next ) {
			    //window.setTimeout( function() {
				$( activeMonths[2].reference ).after( 
				    $( data ) 
				);
				$('#loading-three').css('zIndex', '0');
				setTimeout(
				    function() {
					$('#loading-three').css('zIndex', '-1');
				    },
				1000);
			    //}, 1000);
                        } else if ( prev ) {
			    //window.setTimeout( function() {
				$( activeMonths[0].reference ).before( 
				    $( data ) 
				);
				$('#loading-one').css('zIndex', '0');
				setTimeout(
				    function() {
					$('#loading-one').css('zIndex', '-1');
				    },
				1000);
			    //}, 1000);
                        } else {
			    //window.setTimeout( function() {
			    // filter
				$( '#calendars' ).append( 
				    $(data) 
				);
				$('#loading-one').css('zIndex', '0');
				$('#loading-two').css('zIndex', '0');
				$('#loading-three').css('zIndex', '0');
				setTimeout(
				    function() {
					$('#loading-one').css('zIndex', '-1');
					$('#loading-two').css('zIndex', '-1');
					$('#loading-three').css('zIndex', '-1');
				    },
				1000);
			    //}, 1000);
			}
			toggleMonths( str, exists, filter );
			updateMonthInfo( (typeof filter != 'undefined') ? 'filter' : undefined );
			grabbingData = false;
		    }

                    if ( doXHR ) {
			grabbingData = true;
			    $.ajax({
				type:'GET', url:'/events-get-months.php', data: dateString, success:callback
			    });
                    } else {
			toggleMonths( str, exists, filter );
			updateMonthInfo( (typeof filter != 'undefined') ? 'filter' : undefined );
                    }

		    $.ajax({
			type:'GET',
			url:'/events-listing.php',
			data: (function() {

			    if ( isFilter || hitPrev ) {
				log('its a filter');
				var monthYear = /month=(\d\d?)&year=(\d{4})/;
				dateString = dateString.replace( monthYear, function( string, firstMatch, secondMatch ) {
				    switch ( firstMatch ) {
					case '11':
					    month = 1;
					    year = parseInt( secondMatch ) + 1 ;
					break;

					case '12':
					    month = 2;
					    year = parseInt( secondMatch ) + 1;
					break;

					default:
					    month = parseInt( firstMatch ) + 2;
					    year = secondMatch;
				    }
				    return 'month=' + month + '&year=' + year + '&fid=' + filter;
				})
				return dateString;
			    } else {
				return dateString + '&fid=' + filter;
			    }

			})(),
			success:function(data) {
			    $('#events-listing').html(data);
			    attachListingPopups();
			}
		    });
		}

		function toggleMonths( str, exists, filter ) {
		    var next = ( str == 'next' ) ? 1 : 0,
			prev = ( str == 'previous' ) ? 1 : 0,
			isFilter = (filter) ? 1 :0;

			// next
		    if ( next ) {
			if ( exists && !isFilter ) {
			    var newThird = $( activeMonths[2] ).next()[0].reference;
			    $(newThird).hide();
			    if ( $(activeMonths[2]).next()[0].index > $(activeMonths[2])[0].index ) {
				log('index is greater..');
				$(activeMonths[2].reference).after( newThird )
			    }
			    $(newThird).show();
			}
			var firstActive = activeMonths[0].reference;
			$(firstActive).hide();
			// prev
		    } else if ( prev ) {
			log('prev');
			if ( exists ) {
			    var newFirst = $( activeMonths[0] ).prev()[0].reference;
			    $(newFirst).show();
			}
			var lastActive = activeMonths[2].reference;
			$(lastActive).hide();
		    } else {
			log('duelse');
			var activeCals = $(activeMonths).each(function() {
			    $( $(this)[0].reference ).hide();
			});
		    }
                    $( activeMonths ).each(function() {
			this.active = false;
		    });
		}

		function log( string ) {
		    if ( typeof console != 'undefined') {
			console.log( string );
		    }
		}

		function attachListingPopups() {
		    var listings = $('#events-listing a.location-name');
		    listings.click(function() {
			var dateWrap = $(this).parents('.date-wrap');

			if ( !this.cloned ) {
			    this.cloned = true;
			    clonedContent = dateWrap.clone();
			    clonedContent.addClass('cloned');
			    $(this).before( clonedContent )
			}

			var cloned = $(this).siblings('.cloned');
			cloned
			    .jqm( { toTop:true } )
			    .addClass('modal-content')
			    .addClass('jqmWindow')
			    .jqmShow();

			return false;
		    });
		}

		function attachEventPopups( o ) {
		    $('td.has-event', o).each(function() {

			var dateWrap = $(this).find('.date-wrap'),
			    dateWrapIn = dateWrap.find('.date-wrap-in'),
			    eventDetails = dateWrap.find('div.event-details'),
			    inner = eventDetails.find('.event-details-inner'),
			    obj=this;

			dateWrap.hide();

			eventDetails
			    .addClass('unique')
			    .append( $(this).attr('title') )

			$(this).click(function() {

			    dateWrap.show();
			    dateWrapIn
				.removeClass('alt')
			    eventDetails
				.removeClass('unique')
				.removeClass('alt')

			    dateWrap
				.jqm( { toTop:true } )
				.addClass('modal-content')
				.addClass('jqmWindow')
				.jqmShow();

			    return false;
			});

			$(this).hover(function() {
			    dateWrap.show();
			    dateWrapIn.show();
			    eventDetails.removeClass('alt');
			    inner.fadeIn(70);
			},function(){
			    if ( !window.modalOpen ) {
				dateWrap.hide();
				inner.fadeOut(70);
			    }
			});
		    });
		}

		var loading = $('<div id="loading-one"></div>'),
		loadingTwo = $('<div id="loading-two"></div>'),
		loadingThree = $('<div id="loading-three"></div>');

		$('div#calendars').append( loading );
		$('div#calendars').append( loadingTwo );
		$('div#calendars').append( loadingThree );

		loading.css({
		    'position':'absolute',
		    'background':'#fff url(../images/indicator.gif) no-repeat center center',
		    'top':'0',
		    'width':'192px',
		    'height':'234px',
		    'left':'7px',
		    'z-index':'-1'
		});

		loadingTwo.css({
		    'position':'absolute',
		    'background':'#fff url(../images/indicator.gif) no-repeat center center',
		    'top':'0',
		    'width':'192px',
		    'height':'234px',
		    'left':'206px',
		    'z-index':'-1'
		});

		loadingThree.css({
		    'position':'absolute',
		    'background':'#fff url(../images/indicator.gif) no-repeat center center',
		    'top':'0',
		    'width':'192px',
		    'height':'234px',
		    'left':'405px',
		    'z-index':'-1'
		});

		$('#calendars').css({'position':'relative'});
		
	}
    };

    $(document).ready(function() {

	var eventsCalendarPage = $('body').is('.events-calendar'),
	    safari3 = (typeof window.devicePixelRatio != 'undefined') ? 1 : 0;

	synxis.expandCollapseNews();

	if ( eventsCalendarPage ) {
	    synxis.eventsCalendar();

	    if ( safari3 ) {
		$('div#calendars div.calendar ul.months-list div.month-wrapper table tbody td').css({'height':'22px'});
	    }
	}

	// invoke methods below site-wide
	synxis.flash();
	synxis.sifr();
	// synxis.clientLogin();

    });

})();

