/*****************************************************************************************
 *	Site specific javascript
****************************************************************************************/

var msac = window.msac || {};


msac = (function() {
	
	/* remove quicklinks animation
	var quicklinks = function() {
		
		var config = {
			quicklinksID: 			'#quicklinks',
			quicklinksContentID: 	'#quicklinks-content',
			openWidth: 				'172px',
			closeWidth: 			'30px',
			activeId: 			'quicklinks-active',
			animationSpeed: 		300
		}
		
		// Let's looks it up once
		var $quicklinks 		= $(config.quicklinksID);
		
		$quicklinks.wrap("<div></div>");
		
		// Setup the starting position
		$quicklinks.css('width', config.closeWidth).data(config.activeId, false);
		
		$('h2 a', $quicklinks).bind('click', function(){
			if($quicklinks.data(config.activeId)){
				$quicklinks.animate({width: config.closeWidth}, config.animationSpeed, 'easeOutBounce').data(config.activeId, false).parent().removeAttr('id');
			}
			else {
				$quicklinks.animate({width: config.openWidth}, config.animationSpeed, 'easeOutCubic').data(config.activeId, true).parent().attr('id', config.activeId);
			}
			return false;
		});
	};
	*/

	var initFlash = function() {
		
		if (typeof BASE_URL == 'undefined') return;
		
		if( typeof nid == 'undefined' ) nid = '';
		
		/*/
		// Show alternative content
		$('#flash-alt-content').show();
		
		var flashHeight = 240;
		var siteMode = 'landing';
		if($('body').is('.home-page') || $('body').is('.node-type-oshome')){
			flashHeight = 328;
			siteMode = 'normal';
		}
		
		$('body.home-page #banner, body.node-type-oshome #banner, body.node-type-landing #banner').flash(
			{
				src: BASE_URL + 'Common/flash/swfs/loader.swf',
				id: 'homepage-banner',
				width: '100%',
				height: flashHeight,
				wmode: 'transparent',
				scale: 'noscale',
				flashvars: { 
				xmlPath: SITE_ROOT + 'flash-xml/' + nid,
				//xmlPath: BASE_URL + 'Common/flash/data/data.xml',
				swfPath: BASE_URL + 'Common/flash/swfs/Areeba_MSAC_Header.swf',
				siteMode: siteMode,
				arrowColour: ARROW_COLOR
        }
			},
			{ version: 9 }
		);
		//*/
		
		$('#badge_div').flash(
			{
				src: BASE_URL + 'Common/flash/swfs/badge.swf',
				id: 'msac-widget',
				width: '217',
				height: '180',
				wmode: 'window',
				scale: 'noscale',
				flashvars: { 
					airversion: '1.5',
					appname: 'MSAC Desktop Widget',
					appurl: 'http://www.msac.com.au/sites/default/files/apps/MSACDesktopWidget.air',
					imageurl: BASE_URL + '/Common/images/content/msac-dw.jpg',
					buttoncolor: '1867c4',
					messagecolor: '000000'
	        	}
			},
			{ version: 9 }
		);
		
		$('#page-title h1, #ui-dialog-title-map-dialog, #content-inner h2:not(div.fieldset h2):not(ul.event-details-list h2):not(.custom-block h2):not(.view-store-products td h2):not(.product-view td h2):not(h2.cart-block-title):not(h2.node-as-block), #quicklinks #quicklinks-content h3, .view-store-products th, .product-view th, #cart-form-products th, #uc-cart-checkout-form .fieldset-title, #msac-membership-form .fieldset-title, span.cart-block-title-bar').flashText({
			src: BASE_URL + '/Common/flash/swfs/HelveticaNeueMediumCond_Regular-Bold.swf'
		});		
	};
	
	var allSites = function() {
		$allSites = $('#all-sites');
		$allSites.bind('mouseover', function() {
			$(this).addClass('all-sites-active');
		});
		$allSites.bind('mouseout', function() {
			$(this).removeClass('all-sites-active');
		});
	};
	
	var mapOverlay = function() {
		// append HTML to body at the end // 
		// make this JS a dialog 
		// open the dialog
		
		if($("#map-dialog").length == 0){
			$('body').append('<div id="map-dialog"><iframe width="510" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com.au/maps?f=q&amp;source=s_q&amp;hl=en&amp;geocode=&amp;q=Msac+melbourne&amp;sll=-25.335448,135.745076&amp;sspn=97.61881,58.798828&amp;ie=UTF8&amp;cid=15926256325971222262&amp;ll=-37.831277,144.963913&amp;spn=0.023727,0.036478&amp;z=14&amp;iwloc=A&amp;output=embed"></iframe><br /><small class="larger-map-link"><a href="http://maps.google.com.au/maps?f=q&amp;source=embed&amp;hl=en&amp;geocode=&amp;q=Msac+melbourne&amp;sll=-25.335448,135.745076&amp;sspn=97.61881,58.798828&amp;ie=UTF8&amp;cid=15926256325971222262&amp;ll=-37.831277,144.963913&amp;spn=0.023727,0.036478&amp;z=14&amp;iwloc=A" style="color:#0000FF;text-align:left">View Larger Map</a></small><div class="button-wrapper clearfix"><strong class="description">Find out Tram times:</strong><div class="map-button"><a class="image-replaced" href="http://jp.metlinkmelbourne.com.au">Metlink Journey Planner<span></span></a></div></div></div>');
			$("#map-dialog").css('display','none');
			$("#map-dialog").dialog({
				bgiframe: true,
				autoOpen: false,
				height: 480,
				width: 590,
				title:'How to find us',
				modal: true,
				resizable: false,
				dialogClass: 'map-overlay'
			});
		}
		$('#map-dialog').dialog('open');
	};
	
	var jqueryUI = function() {
		$('ul.accordion').accordion({ header: 'h3', autoHeight: false });
		$('div.tabs').tabs();
		$('div.tabs ul.ui-tabs-nav li').addClass('ui-corner-all');
		$('div.calendar-accordion').accordion({ header: 'h3', autoHeight: false });
		$('#find-link').click(function() { mapOverlay(); return false; })
	};
	
	
	var helperHover = function(el){
		 
		 $(el).hover(
			function() { $(this).addClass('arb-hover ui-state-hover'); },
			function() { $(this).removeClass('arb-hover ui-state-hover'); }
		);
		 
	};
	
	var fadeImage = function() {
		$buttons = $(".fade-image");
		$buttons.removeClass("fade-alt")
		$("span.hover", $buttons).addClass('test').css('display', 'none'); /* set display none on the element which overrides the css declaration when the button is hovered */
		$buttons.hover(
			function() {
				$("span.hover", this).fadeIn(400);
			},
			function() {
				$("span.hover", this).fadeOut(200);
			}
		);
	};
	 
	var pageControls = function(){
		if($('body.maintenance-section').length < 1){
			arb.functions.fontSizing('#page-controls-box ul', {
				insertHTML: '<li id="font-size-down-control" class="image-replaced" title="Decrease font size">A-<span></span></li><li id="font-size-up-control" class="image-replaced" title="Increase font size">A+<span></span></li><li class="print-link"><a href="#" title="Print page">Print Page</a></li>'
			});
		}
	}
	
	/* To add rollovers and click states to <img> and <input type="image"> tags */
	var imageHelper = function(){
		$('#search-theme-form input.button').imageHelper({
			doClick: true
		});
	}
	
	/*
	 * 		hover navigation
	 */
	var initPrimaryNavigation = function() {
		
			var timeoutID;
			
			if ($('body.store-section').length > 0 || $('body.cart-section').length > 0) {
				return;
			}
			
			// Only Grab the top level <a> links
			$('#primary-navigation > ul > li > a').each(function() {
				var container = $(this).parent();
								
				var subMenu = container.children('ul');
				container.bind("mouseover", function() {window.clearTimeout(timeoutID);});
				
				if (subMenu.length > 0) {
					container.hoverIntent(
						function() {
							if (!container.is(".expanded")) {
								expand(container, subMenu);
							}
						  },
						function() {; }
					);
				}
				else {
					container.addClass("leaf");
					if (container.is(".active")) {
						container.addClass("active-leaf");				 
					}
				}
			});
		
			$("#primary-navigation > ul").hoverIntent(
				function() {;},
				function() {
					window.clearTimeout(timeoutID);
					timeoutID = window.setTimeout(function() {
						$("#primary-navigation ul ul:not(:has(li.active))").each(function() {
							contract($(this).parent(), $(this));											
						});
					},
					750);
				}
			);
		
			function expand(container, subMenu) {
				subMenu.slideDown('fast', function(){
					container.removeClass("animating");
					$(this).height("auto");
				});
				container.addClass("expanded");
			}
			
			function contract(container, subMenu) {
				
				// Don't hide the active menu item
				if($(container).is('.active')){
          
        }
				else {
					subMenu.slideUp('fast', function(){
          container.removeClass("animating");
	          $(this).height("auto");
	        });
	        container.removeClass("expanded") 
				}
        
				
							
			}
		}
	
	// stort sort function puts background image arrow before sifr replaces it
	
	var storePreFlash = function () {
		$('.view-store-products th a.active').each(function() {
			var href = $(this).attr('href');
			var sort = gup(href, 'sort');
			//$(this).parent().addClass('active');
			$(this).parent().addClass('sort-'+sort);
		});

		$('.cart-block-title-bar').each(function(){
			$(this).parent().addClass('cart-block-title');
			//$(this).parent().parent().prepend('<a href="/cart"><span title="View your shopping cart." class="cart-block-icon-full"></span></a>');
		});
		
		$('.cart-block-icon-full').each(function(){
			$(this).parent().parent().addClass('cart-block-title-full');
		});
		
		$('.cart-block-icon-empty').each(function(){
			$(this).parent().parent().addClass('cart-block-title-empty');
		});

		// breakdown a url [http://www.netlobo.com/url_query_string_javascript.html]
		function gup(url, name) {
		  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		  var regexS = "[\\?&]"+name+"=([^&#]*)";
		  var regex = new RegExp( regexS );
		  var results = regex.exec(url);
		  if( results == null )
		    return "";
		  else
		    return results[1];
		}
	}
	
	var storePostFlash = function () {
		$('.cart-block-title-full').each(function(){
			$(this).prepend('<a href="/cart"><span title="View your shopping cart." class="cart-block-icon-full"></span></a>');
		});
		$('.cart-block-title-empty').each(function(){
			$(this).prepend('<a href="/cart"><span title="View your shopping cart." class="cart-block-icon-empty"></span></a>');
		});
		//$('.cart-block-title').removeClass('cart-block-title');
		
	}
	
	var storeCheckout = function () {
		$('#checkout-form-bottom').addClass('feature-link');
		$('#checkout-form-bottom a.link-button').eq(0).addClass('edit-cancel').wrap('<div class="feature-back">');
		$('#uc-cart-checkout-review-form a.link-button').eq(0).addClass('edit-back').wrap('<div class="feature-back">');
		
		// kill the sticky on the tables
		$("#cart-form-pane .sticky-header").remove();
		$(".order-review-table .sticky-header").remove();

		if ($('#uc-cart-checkout-form').length > 0) {
			addSteps();			
			
			var loc = window.location;
			var hash = loc.hash;
			
			$('#uc-cart-checkout-form').prepend('<a name="delivery"></a><a name="payment"></a>');
			$('#uc-cart-checkout-form #cart-pane').hide();
			
			var error = false;
			var errorPayment = false;
			
			if ($('div.error').length > 0 ) {
				error = true;
				if ($('div#delivery-pane input.error, div#customer-pane input.error').length == 0) {
					errorPayment = true;
				}
			}
			
			if (hash == '#payment' || errorPayment) {
				setPane('payment');
			} else {
				setPane('delivery');
			} 
		}
		
		if ($('table.order-review-table').length > 0) {
			addSteps();
			$('.checkout-links').addClass('checkout-links-review');
		}
		
		if ($('.cart-checkout-complete-page #main-inner').length > 0) {
			addSteps();
		}
		
		function addSteps() {
			$('#main-inner').prepend('<div class="checkout-links"></div>');
		}
		
		function setPane(pane) {
			switch(pane) {
				case 'delivery':
					$('.checkout-links').removeClass('checkout-links-payment');
					$('.checkout-links').addClass('checkout-links-delivery');
					
					$('#uc-cart-checkout-form #billing-pane').hide();
					$('#uc-cart-checkout-form #quotes-pane').hide();
					$('#uc-cart-checkout-form #payment-pane').hide();
					$('#uc-cart-checkout-form #comments-pane').hide();
					$('#uc-cart-checkout-form #billing-pane').hide();
					$('#uc-cart-checkout-form #coupon-pane').hide();
					$('#checkout-form-bottom a.link-button').eq(1).hide();
					
					$('#uc-cart-checkout-form #custom-pane').hide();

					$('#uc-cart-checkout-form #customer-pane').show();
					$('#uc-cart-checkout-form #delivery-pane').show();
					
					$('#checkout-form-bottom').append('<a href="#payment" id="payment-link"><span>Payment</span></a>');
					$('#checkout-form-bottom a#payment-link').click(function(){
						return validatePane('delivery');
					});
					$('#checkout-form-bottom a#delivery-link').remove();
					break;
				case 'payment':
					$('.checkout-links').addClass('checkout-links-payment');
					$('.checkout-links').removeClass('checkout-links-delivery');
					
					$('#uc-cart-checkout-form #billing-pane').show();
					$('#uc-cart-checkout-form #quotes-pane').show();
					$('#uc-cart-checkout-form #payment-pane').show();
					$('#uc-cart-checkout-form #comments-pane').show();
					$('#uc-cart-checkout-form #billing-pane').show();
					$('#uc-cart-checkout-form #coupon-pane').show();
					$('#checkout-form-bottom a.link-button').eq(1).show();
					$('#checkout-form-bottom a.link-button').eq(1).addClass('review-order').after('<span class="feature-back"><a href="#delivery" id="delivery-link" class="form-submit"><span>Delivery</span></a><span>');
					$('#checkout-form-bottom a#delivery-link').click(function(){
						setPane('delivery');
					});
					
					$('#uc-cart-checkout-form #custom-pane').show();

					$('#uc-cart-checkout-form #customer-pane').hide();
					$('#uc-cart-checkout-form #delivery-pane').hide();
					$('#checkout-form-bottom a#payment-link').remove();
					break;
			}
		}
		
		function validatePane(pane) {
			var errors = new Array();
			var num = 0;
			switch(pane) {
				case 'delivery':
					$('#uc-cart-checkout-form #delivery-pane .required, #uc-cart-checkout-form #customer-pane .required,').each(function(){
						if ($(this).val() == '') {
							$(this).addClass('error');
							errors[num] = this;
							num++;
						} else {
							$(this).removeClass('error');
						}
					});
					//console.log(num);
					if (num == 0) {
						if ($('div.messages').length == 0) {
							$('.checkout-links').after('<div class="messages error"></div>');
						}
						$('div.messages').remove();
						setPane('payment');
						return true;
					} else {
						if ($('div.messages').length == 0) {
							$('.checkout-links').after('<div class="messages error"></div>');
						}
						$('div.messages').html('<ul><li>Please complete the required fields marked with an *.</li></ul>');
						
						return false;
					}
			}
			
		}
		
		function setButtons(target) {
			addButton(target);
		}
		
		function addButton(button) {
			switch (button) {
				case 'payment':
					$('.checkout-links').prepend('<a href="/cart/checkout#payment" class="checkout-payment image-replaced">Payment<span></span></a>');
				case 'delivery':
					$('.checkout-links').prepend('<a href="/cart/checkout#delivery" class="checkout-delivery image-replaced">Delivery<span></span></a>');
					break;
			
			}
		}
	}
	
	var widgetBadge = function () {
		/*
		var flashvars = {};

		flashvars.airversion = '1.5';
		flashvars.appname = 'MSAC Desktop Widget';
		flashvars.appurl = 'http://www.msac.com.au/sites/default/files/MSACDesktopWidget.air';
		flashvars.imageurl = '/sites/all/themes/customtheme/Common/images/content/msac-dw.jpg';
		flashvars.buttoncolor='1867c4';
		flashvars.messagecolor='FFFFFF';

		var params = {};
		params.wmode = 'window';
		params.menu = 'false';
		params.quality = 'high';

		var attributes = {};

		swfobject.embedSWF('/sites/all/themes/customtheme/Common/flash/swfs/badge.swf', 'badge_div', '217', '180', '9.0.115', '/sites/all/themes/customtheme/Common/flash/swfs/expressInstall.swf', flashvars, params, attributes);
		*/
	}
	
	return  { // Everything that is returned in this object literal will be public
		
		init: function() {
		
			initPrimaryNavigation();
			pageControls();
			// quicklinks();
			// allSites();
			jqueryUI();
			helperHover('div.button a');
			helperHover('input.form-submit');
			arb.functions.linkButtons('div.buttons-form-item input');
			arb.functions.linkButtons('div.add-to-cart input.form-submit');
			arb.functions.linkButtons('div#cart-form-buttons input.form-submit');
			arb.functions.linkButtons('#checkout-form-bottom input.form-submit');
			arb.functions.linkButtons('#uc-cart-checkout-review-form input.form-submit');
			arb.functions.linkButtons('#msac-membership-form input.form-submit');
			$("#main form div.form-item").eq(0).addClass("first-form-item");			
			// before sifr runs, run the store sort column function
			storePreFlash();
			initFlash();
			storePostFlash();
			storeCheckout();
			imageHelper();
			fadeImage();
			
		}
		
	};

})(); // Invoke the function creating a closure and assign the returned object literal



/**
 * Let's get it started
 */
$(document).ready(function() {
	msac.init();
});

