jQuery(document).ready(function(){

	// fix chinese main nav item from link to "Coming Soon" before receiving chinese content
	jQuery('.chinese-about').html("<a href='' style='height:50px' onclick='return false'>Chinese About<a>");
	
	// Regular expression to test email
	var EMAIL_FILTER = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
	//var EMAIL_FILTER = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$([\s]*)/; 
	
	
	// clear form fields on click
	jQuery("#subscribeForm #elqfirstname, #subscribeForm #elqlastname, #subscribeForm #elqemailaddress, #appForm #elqfirstname, #appForm #elqlastname, #appForm #elqemailaddress").click(function(){
	
		jQuery(this).val("");
	});
	
	
	/*  ELOQUA FORM INTEGRATION
	 *  author: Natasha Rooney
	 *  date: 06/07/2011
	 *  
	 *  FOR THIS METHOD TO WORK YOU MUST GIVE A DIV WRAPPING THE FORM THE CLASS ".aMACform" 
	 *  AS WELL AS THE formName IN THE SAME DIV - THIS DIV MUST ENCAPSULATE ALL INPUTS AND SELECTS
	 *  FOR THE FORM INCLUDING HIDDEN FIELDS. 
	 *
	 *  PARAMS: 
	 *  formName - name of div wrapping aroung form. Not necessarily main parent div. 
	 *  submitButtonClass - class attached to the submit button of the new form 
	 *  checkEmail - boolean to detect whether to validate an email field
	 *  emailFieldSelector - jQuery selector for the email field, needed if to check valid email, leave as null or empty string if not needed
	 *  emailMessage - jquery selector for div to show when email isn't valid
	 *  checkNotEmptyFields - boolean to detect whether to validate a not empty field
	 *  notEmptyFieldsArray - array of all fields that cannot be empty, key/value pair is id_of_input/div_to_display name e.g. 
	 			id=C_Company / <div id="notEmpty" name="formCompany">Please enter</div> 
	 *  checkDropDownFields - boolean to detect whether to check the dropdown fields
	 *  dropDownFieldsArray - array of all drop down fields
	 *  actionVal - new action value for the form, location of where the form will be sent
 
		<div id="forceSelect" name="formCountry">Please select</div> id=C_Home_Country1
		<div id="notEmpty" name="formSurname">Please enter</div>  id=C_LastName 
		<div id="notEmpty" name="formCompany">Please enter</div> id=C_Company 
		<div id="notEmpty" name="formName">Please enter</div>  id=C_FirstName
		<div id="validEmailContact">Please enter valid email address</div> 
 
 	 */
 	 
 	// DISABLING ALL SUBMIT ELEMENTS
	jQuery(":submit").attr('disabled', 'disabled');
	
	// find what pathname is so we can check what page we are on
	var pathnameArray = window.location.pathname.split('/');
	var pathname = pathnameArray[pathnameArray.length-1];

 	 
 	// SUBSCRIBE FORM: called on every page
	eloquaFormHack("#subscribeForm", ".subscribeFormSubmit", 1, '#elqemailaddress', "#validEmailMessage", 0, null, 0, null, "http://now.eloqua.com/e/f2.aspx");
	
	// APP PLANET FORM: called on APP PLANET pages
	eloquaFormHack("#appForm", ".appFormSubmit", 1, '#elqemailaddress', "#validEmailMessage", 0, null, 0, null, "http://now.eloqua.com/e/f2.aspx");
	
	// CONTACT PAGE FORM: only call if on /contact page
	if(pathname == "contact.html"){	
		var notEmptyFields = [];
			notEmptyFields["#C_FirstName"] = 'div[name|="formName"]';
			notEmptyFields["#C_LastName"] = 'div[name|="formSurname"]';
			notEmptyFields["#C_Company"] = 'div[name|="formCompany"]';
		var dropDownFields = [];
			dropDownFields["#C_Home_Country1"] = 'div[name|="formCountry"]';
		
		eloquaFormHack("#contactPageForm", ".contactPageFormSubmit", 1, '#contactC_EmailAddress', "#validEmailContact", 1, notEmptyFields, 1, dropDownFields, "http://now.eloqua.com/e/f2.aspx");
	}
	
	// WHO ATTENDS MAC FORM: only call if on /who-attends page
	if(pathname == "who-attends.html"){	
		var notEmptyFields = [];
			notEmptyFields["#C_FirstName"] = 'div[name|="whoformName"]';
			notEmptyFields["#C_LastName"] = 'div[name|="whoformSurname"]';
			notEmptyFields["#C_Company"] = 'div[name|="whoformCompany"]';
		var dropDownFields = [];
			dropDownFields["#C_Home_Country1"] = 'div[name|="whoformCountry"]';
		
		eloquaFormHack("#whoAttendsForm", ".whoAttendsFormSubmit", 1, '#whoC_EmailAddress', "#whovalidEmailContact", 1, notEmptyFields, 1, dropDownFields, "http://now.eloqua.com/e/f2.aspx");
	}
	
	// EBROCHURE MAC FORM: only call if on /who-attends page
	if(pathname == "brochure"){	
		var notEmptyFields = [];
			notEmptyFields["#C_FirstName"] = 'div[name|="ebrochureFirstName"]';
			notEmptyFields["#C_LastName"] = 'div[name|="ebrochureLastName"]';
			notEmptyFields["#C_Company"] = 'div[name|="ebrochureCompany"]';
		var dropDownFields = [];
			dropDownFields["#C_Home_Country1"] = 'div[name|="ebrochureCountry"]';
		
		eloquaFormHack("#eBrochureForm", ".ebrochuresubmit", 1, '#C_EmailAddress', "#ebrochureEmail", 1, notEmptyFields, 1, dropDownFields, "http://now.eloqua.com/e/f2.aspx")
	}
	
	// CFP FORM: only call on /cfp page
	if(pathname == "cfpform.html"){	
		eloquaFormHack("#cfpForm", "#cfpFormSubmit", 0, null, null, 0, null, 0, null, "http://www.response-o-matic.com/mail.php");
	}
	
	// main function for beating the webgen eloqua form clash! bring it on ...
	function eloquaFormHack(
						formName, 
						submitButtonClass, 
						checkEmail, 
						emailFieldSelector, 
						emailMessage, 
						checkNotEmptyFields, 
						notEmptyFieldsArray, 
						checkDropDownFields, 
						dropDownFieldsArray, 
						actionVal){
	
		// TURN ON CORRECT SUBMIT WHEN TYPING IN FIELD, TURN OFF OFF IF SWITCH TO ANOTHER FIELD 	
		jQuery(formName + " input, " + formName + " select, " +  formName + " input:checkbox,"  +  formName + " textarea" ).focus(function() {
			jQuery(":submit").attr('disabled', 'disabled');
			jQuery(submitButtonClass).removeAttr('disabled');
		});
		jQuery(formName + " input:checkbox").click(function() {
			jQuery(":submit").attr('disabled', 'disabled');
			jQuery(submitButtonClass).removeAttr('disabled');
		});
	
 
		jQuery(submitButtonClass).click(function(event){
		
			var validationComplete = 1; //assume validation is complete, allow the code to recognise it is not complete with validationComplete = 0;
		
			//validate email
			if(checkEmail == 1){
				var email = jQuery(emailFieldSelector).val();
		
				if(!EMAIL_FILTER.test(email)){
					event.preventDefault();
					jQuery(emailMessage).css("visibility","visible");
					validationComplete = 0;
				}
				else{
						jQuery(emailMessage).css("visibility","hidden");
				}
			}
			
			//check notEmpty fields are not empty
			if(checkNotEmptyFields == 1){
				for (i in notEmptyFieldsArray) { 
					var fieldVal = jQuery(i).val();
					
					if(fieldVal == null || fieldVal == ""){
						event.preventDefault();
						jQuery(notEmptyFieldsArray[i]).css("visibility","visible");
						validationComplete = 0;
					}
					else{
						jQuery(notEmptyFieldsArray[i]).css("visibility","hidden");
					}
				};
			}
			
			//check drop down box item is selected
			if(checkDropDownFields == 1){
				for (i in dropDownFieldsArray) { 
					var fieldVal = jQuery(i).val();
					
					if(fieldVal == null || fieldVal == ""){
						event.preventDefault();
						jQuery(dropDownFieldsArray[i]).css("visibility","visible");
						validationComplete = 0;
					}
					else{
						jQuery(dropDownFieldsArray[i]).css("visibility","hidden");
					}
				};
			}


			// if validation is complete, then submit form
			if(validationComplete == 1){			
		 		jQuery('form').removeAttr("name");
				jQuery('form').removeAttr("onsubmit");
				jQuery('form').removeAttr("id");
				jQuery('form').removeAttr("autocomplete");
				
				//Hack on original form input fields
				jQuery("#__EVENTARGUMENT").wrap('<div></div>').parent().html("");
				jQuery("#__EVENTTARGET").wrap('<div></div>').parent().html("");
				jQuery("#__EVENTVALIDATION").wrap('<div></div>').parent().html("");
				jQuery("#__VIEWSTATE").wrap('<div></div>').parent().html("");
				jQuery("#page_sidebar_loginstatus_flexLoginStatus_txtPasswordLoginPanel").wrap('<div></div>').parent().html("");
				jQuery("#page_sidebar_quicksearch_flexQuickSearch_txtQuickSearch").wrap('<div></div>').parent().html("");
				jQuery("#page_sidebar_loginstatus_flexLoginStatus_txtEmailLoginPanel").wrap('<div></div>').parent().html("");
	
	
				//kill all other forms as to not confuse eloqua
				jQuery(".aMACform").not(formName).html("");
	
				// change to Eloqua action
				jQuery('form').attr("action", actionVal);
			}
		});	
		
		// Finding a match between an email rgex and an email string on keyup event
		if(checkEmail == 1){
			jQuery(emailFieldSelector).keyup(function(event) {
				
				var email = jQuery(this).val();
				
				// test method finds match between a javascript regular expression and string
				if(!EMAIL_FILTER.test(email)){ 
					//jQuery(emailMessage).html("no");
				}
				else {
					//jQuery(emailMessage).html("yes");
					jQuery(formName + " " + emailMessage).css("visibility","hidden");	
				}
				
			});
		}
	}

	/*  MAIN NAVIGATION ROLLOVER
	 *  author: Natasha Rooney
	 *  date: 13/07/2011
 	 */
 	 
 	//chinese
 		jQuery("#header").append("<div class='rollover navChinese' style='display:none'><ul><li>即将推出</li></ul><div>");
 		jQuery(".chinese-about a, .navChinese").mouseover(function() {
			jQuery('.navChinese').css('display','block');
		}).mouseout(function(){
			jQuery('.navChinese').css('display','none');
		});
	
	makeRollover('#subnavAbout_MAC', 'navAbout_MAC', '.about');
	makeRollover('#subnavConference', 'navConference', '.conference');
	makeRollover('#subnavExhibition', 'navExhibition', '.exhibition');
	makeRollover('#subnavNetworking', 'navNetworking', '.networking');
	makeRollover('#subnavAppplanet', 'navAppplanet', '.appplanet');
	makeRollover('#subnavSponsor', 'navSponsor', '.be-a-part');
	makeRollover('#subnavRegistration', 'navRegistration', '.registration');
	makeRollover('#subnavTravel', 'navTravel', '.travel');
	makeRollover('#subnavInteract', 'navInteract', '.interact');
	
	function makeRollover(from, to, menuItem){
		var rolloverItems = jQuery(from).children('ul').html();
		jQuery("#header").append("<div class='rollover "+ to +"' style='display:none'><ul>" + rolloverItems + "</ul><div>");
		
		var to = "." + to;
		jQuery(menuItem + " a, " + to).mouseover(function() {
			jQuery(to).css('display','block');
		}).mouseout(function(){
			jQuery(to).css('display','none');
		});
		

	}
	
	/*  LEFT NAVIGATION, LEFT NAVIGATION ONPAGE LINK COLOUR CHANGE & BREADCRUMB 
	 *  author: Natasha Rooney
	 *  date: 13/07/2011
 	 */
 	leftNavAndBreadcrumb("About_MAC", "#subnavAbout_MAC"); 
	leftNavAndBreadcrumb("Conference", "#subnavConference"); 
 	leftNavAndBreadcrumb("Exhibition"	, "#subnavExhibition"); 
	leftNavAndBreadcrumb("Networking", "#subnavNetworking"); 	
 	leftNavAndBreadcrumb("Appplanet", "#subnavAppplanet"); 
	leftNavAndBreadcrumb("Sponsor/Partner", "#subnavSponsor"); 
 	leftNavAndBreadcrumb("Registration", "#subnavRegistration"); 
	leftNavAndBreadcrumb("Travel", "#subnavTravel"); 
 	leftNavAndBreadcrumb("Interact", "#subnavInteract"); 
 	leftNavAndBreadcrumb("Press", "#subnavPress");
	
	function leftNavAndBreadcrumb(name, from){
	
		name = '[name*="' + name + '"]';
		var subnavCat = "";
	
		if(jQuery('#leftnavcontent').is(name)){
			var selector = from;
		    var subnav = jQuery(selector).children('ul').html(); 
			jQuery('#leftnavcontent' + name).html("<ul>" + subnav + "</ul>");
			
			//prep for breadcrumb
			var pathnameArray = window.location.pathname.split('/');
			var pathname = pathnameArray[pathnameArray.length-1];

			// breadcrumb
			var breadcrumb = "<a href='http://mobileasiacongress.com/'>Home</a> > "
			breadcrumb = breadcrumb + jQuery(selector).children('a').clone().wrap('<div></div>').parent().html();

			jQuery('#leftnavcontent a').each(function(){
			
			var linkArray = jQuery(this).attr("href").split('/');
			var link = linkArray[linkArray.length-1];
			
			if(pathname == link){
				jQuery(this).css("color","red");
				breadcrumb = breadcrumb + " > <span style='color:red'>" + jQuery(this).html() + "</span>";
			}
			
			});
			
			
			
			
			if(jQuery('body').hasClass('page-articles'))
			{
				breadcrumb = "<a href='/'>Home</a> > <a href='/press'>Press</a> > <a href='/press-releases'>Press Releases</a>";
				jQuery('#breadcrumb').html(breadcrumb); 
			
			}
			else{
				jQuery('#breadcrumb').html(breadcrumb);
			}
			
		}	
	}

	
	/*  HOMEPAGE TABBED CONTENT
	 *  author: Natasha Rooney
	 *  date: 30/06/2011
 	 */
	
	jQuery.expr[':'].regex = function(elem, index, match) {
	    var matchParams = match[3].split(','),
	        validLabels = /^(data|css):/,
	        attr = {
	            method: matchParams[0].match(validLabels) ?
	                        matchParams[0].split(':')[0] : 'attr',
	            property: matchParams.shift().replace(validLabels,'')
	        },
	        regexFlags = 'ig',
	        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
	    return regex.test(jQuery(elem)[attr.method](attr.property));
	}

	
	jQuery(':regex(id,^button)').click(function() { 
	
		var some_string = jQuery(this).attr('id');	
		var patt1 = new RegExp("[0-9]+");
		var tabNumber = patt1.exec(some_string);		
		
		jQuery(':regex(id,^tab)').css('display','none');
		jQuery(':regex(id,^button)').removeClass("on");
		jQuery("#tab"+tabNumber).css('display','block');
		jQuery("#button"+tabNumber).addClass("on");
	});
	
	
	
	/*  FOOTER SLIDER
	 *  author: Natasha Rooney
	 *  date: 26/09/11
 	 */
 	
	jQuery('#platinummedia_slider').nivoSlider({
        effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
        animSpeed: 500, // Slide transition speed
        pauseTime: 3000, // How long each slide will show
        directional: false, // Next & Prev navigation
        directionNavHide: false, // Only show on hover
        controlNav: false, // 1,2,3… navigation
        prevText: '', // Prev directionNav text
        nextText: '', // Next directional text
    });
   jQuery('#gsmasites_slider').nivoSlider({
        effect: 'fade', // Specify sets like: 'fold,fade,sliceDown'
        animSpeed: 500, // Slide transition speed
        pauseTime: 3000, // How long each slide will show
        directional: false, // Next & Prev navigation
        directionNavHide: false, // Only show on hover
        controlNav: false, // 1,2,3… navigation
        prevText: '', // Prev directionNav text
        nextText: '', // Next directional text
    });


});
