jQuery(document).ready(function(){
	/****************************************************************************************/
	/*See if there's anything to focus on load												*/
	/****************************************************************************************/
	jQuery(".focusonload").focus();
	/****************************************************************************************/



	/****************************************************************************************/
	/*Buttons																				*/
	/****************************************************************************************/
	jQuery("input#submit").before("<div class='btnLeft'>&nbsp;</div>");
	jQuery("input#submit").after("<div class='btnRight'>&nbsp;</div>");
	jQuery("input#submit").next("div.btnRight").addClass("noClear");
	
	jQuery("input.button").before("<div class='btnLeft'>&nbsp;</div>");
	jQuery("input.button").after("<div class='btnRight'>&nbsp;</div>");
	jQuery("input.noClear").next("div.btnRight").addClass("noClear");
	
	jQuery("div.btnRight:not(.noClear)").after("<br class='clearLeft' />");	
	/****************************************************************************************/



	/****************************************************************************************/
	/*Activate or Deactivate user links														*/
	/****************************************************************************************/
	$("#activateLink").live("click", function(){
		var username = $("#username").html();
		
		$.ajax({ 
		   	type: "POST",
		   	async: true,
		   	context: document.body,
			url: "includes/forms/activateUser.php",
			data: "username="+username,
			success: function(){
        		$("#userStatus").html("<span class='formValue active'><strong>Actif</strong> - <a href=\"#\" id=\"deactivateLink\">D&eacute;sactiver ce compte</a></span>");
	    	}
	    });
	    return false;
	});
	
	$("#deactivateLink").live("click", function(){
		var username = $("#username").html();
		
		$.ajax({ 
		   	type: "POST",
		   	async: true,
			url: "includes/forms/deactivateUser.php",
			data: "username="+username,
			success: function(){
        		$("#userStatus").html("<span class='formValue inactive'><strong>Inactif</strong> - <a href=\"#\" id=\"activateLink\">Activer ce compte</a></span>");
	    	}
	    });
	});	
	/****************************************************************************************/
	
	

	/****************************************************************************************/
	/*Blog headlines ticker																	*/
	/****************************************************************************************/
	$('#js-news').ticker({
		speed: 0.2,
		titleText: 'Bulletins'
	}) 
	/****************************************************************************************/



	/****************************************************************************************/
	/*Fixed secure badge																	*/
	/****************************************************************************************/
	if($('#secure_badge').offset()){
		var top = $('#secure_badge').offset().top;
	
		$(window).scroll(function(e) {
			// what the y position of the scroll is
			var y = $(this).scrollTop();
			
			// whether that's below the form
			if (y >= top) {
			  // if so, ad the fixed class
			  $('#secure_badge').addClass('fixed');
			} else {
			  // otherwise remove it
			  $('#secure_badge').removeClass('fixed');
			}
		});
	}
	/****************************************************************************************/



	/****************************************************************************************/
	/*Datepicker for installs																*/
	/****************************************************************************************/
	$.datepicker.regional['fr'] = {
			closeText: 'Fermer',
			prevText: '&#x3c;Préc',
			nextText: 'Suiv&#x3e;',
			currentText: 'Courant',
			monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
			'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
			monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
			'Jul','Aoû','Sep','Oct','Nov','Déc'],
			dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
			dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
			dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
			weekHeader: 'Sm',
			dateFormat: 'dd/mm/yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['fr']);
	$('#installDate').datepicker();
	/****************************************************************************************/
	
	

	/****************************************************************************************/
	/*Label over inputs																		*/
	/****************************************************************************************/
	$('label.labelOver').labelOver('over-apply');
	/****************************************************************************************/
	


	/****************************************************************************************/
	/*Top banner cycle - this is only on front page											*/
	/****************************************************************************************/
	if(jQuery("#banner").cycle){
		jQuery('#banner').cycle({
    		fx:      'fade',
		    timeout:  7000
    		/*easing:  'easeInOutBack'*/
		});
	}
	/****************************************************************************************/	
	
	
	
	/****************************************************************************************/
	/*Hide those ugly borders on radio buttons - anywhere there's a form					*/
	/****************************************************************************************/
	jQuery("input:radio").css("border", "none");
	/****************************************************************************************/
	
	
	
	/****************************************************************************************/
	/*On accessory sku mouseover, display the picture, hide on mouseout - only on 			*/
	/*accessories page in online portal														*/
	/****************************************************************************************/
	jQuery("td.accessorySku a").live('mouseover mouseout', function(event){
		if(event.type == 'mouseover'){
			var sku = jQuery(this).html();
			var elem = "#img" + sku;
			jQuery(elem).css("left", event.pageX + 30);
			jQuery(elem).css("top", event.pageY + 20);
			jQuery(elem).css("display", "block");
		} else {
			var sku = jQuery(this).html();
			var elem = "#img" + sku;
			jQuery(elem).css("display", "none");
		}
	});
	/****************************************************************************************/
	


	/****************************************************************************************/
	/*Initialize addresses page																*/
	/****************************************************************************************/		
	if(jQuery("#shippingMethodPickup").is(":checked")){
		jQuery("#shippingContainer").hide();
	}
	jQuery("#shippingMethodPickup").click(function(){
		jQuery("#shippingContainer").hide();
	});
	jQuery("#shippingMethodCourrier").click(function(){
		jQuery("#shippingContainer").show();
	});
	
	jQuery("#newBillingAddress").hide();
	jQuery("#useBillingAddressSaved").click(function(){
		jQuery("#newBillingAddress").hide();
	});
	jQuery("#useBillingAddressNew").click(function(){
		jQuery("#newBillingAddress").show();
	});

	jQuery("#newShippingAddress").hide();
	jQuery("#useShippingAddressSame").click(function(){
		jQuery("#newShippingAddress").hide();
	});
	jQuery("#useShippingAddressSaved").click(function(){
		jQuery("#newShippingAddress").hide();
	});
	jQuery("#useShippingAddressNew").click(function(){
		jQuery("#newShippingAddress").show();
	});
	/****************************************************************************************/		



	/****************************************************************************************/
	/*Initialize PAE order page																*/
	/****************************************************************************************/	
	jQuery("#shippingAddressContainer").hide();
	jQuery("#storePickupContainer").hide();
	/****************************************************************************************/	
	
	
	
	/****************************************************************************************/
	/*Show payment methods																	*/
	/****************************************************************************************/
	jQuery("#paymentMethod0").click(function(){
		jQuery("#storePickupContainer").hide();
		jQuery("#shippingAddressBlockContainer").slideDown();
	});
	jQuery("#paymentMethodCC").click(function(){
		jQuery("#storePickupContainer").hide();
		jQuery("#shippingAddressBlockContainer").slideDown();
	});
	jQuery("#paymentMethodStore").click(function(){
		jQuery("#shippingAddressBlockContainer").hide();
		jQuery("#storePickupContainer").slideDown();
	});
	
	//Update available/selected payment methods on CC blur
	jQuery("#subscriberCreditCardNumber").blur(function(){
		if(jQuery(this).val() != ""){//We should have a CC number here
			jQuery("#paymentMethodCC").attr("disabled", false);
			
			if(jQuery("#totalAmount").val() != "0.00$"){//We have something to pay - default to CC
				jQuery("#paymentMethodCC").attr("checked", true);
				jQuery("#storePickupContainer").hide();
				jQuery("#shippingAddressBlockContainer").slideDown();
			}
		} else {//No CC number
			if((jQuery("#paymentMethodCC").val() != "0.00$") && jQuery("#paymentMethodCC").is(":checked")){//Check if we had it selected
				//We need to change it - let's decide what we change it to
				if(jQuery("#totalAmount").val() == "0.00$"){//0$ - set it accordingly
					jQuery("#paymentMethod0").attr("checked", true);
				} else {//Not 0$ - use local pickup
					jQuery("#paymentMethodStore").attr("checked", true);
					jQuery("#shippingAddressBlockContainer").hide();
					jQuery("#storePickupContainer").slideDown();
				}
				jQuery("#paymentMethodCC").attr("disabled", true);
			}
		}
	});
	/****************************************************************************************/

	
	
	/****************************************************************************************/
	/*Setup triggers to update the cart total												*/
	/****************************************************************************************/	
	jQuery("input.accessoryItem").live("click", function(){
		updateTotal();
	});
	jQuery("#phoneModel").change(function(){
		updateTotal();
	});
	/****************************************************************************************/	
	
		
	
	/****************************************************************************************/
	/*Get an updated total and post it														*/
	/****************************************************************************************/
	function updateTotal(){
		var total = 0;
		var pos = 0;
		var str = "";
		var price = 0;
		
		//Accessories
		jQuery("input.accessoryItem").each(function(index){
			if(jQuery(this).is(":checked")){
				str = jQuery(this).next("span").html();
				pos = str.lastIndexOf("-");
				price = str.substr(pos+2);
				price = price.substr(0, price.length -1);
				total += parseFloat(price);
			}
		});
		
		//Phone
		str = jQuery("#phoneModel option:selected").text();
		pos = str.lastIndexOf("-");
		price = str.substr(pos+2);
		price = price.substr(0, price.length -1);
		total += parseFloat(price);
		total = total.toFixed(2);
		
		jQuery("#totalAmount").val(total+"$");
		
		//Change payment methods
		if(total > 0){
			jQuery("#paymentMethod0").attr("disabled", true); //Disable it
			if(jQuery("#paymentMethod0").is(":checked")){
				if(jQuery("#subscriberCreditCardNumber").val() != ""){//We have a CC number - default to use it
					jQuery("#paymentMethodCC").attr("checked", true);
				} else {//No CC number, default to store pickup
					jQuery("#paymentMethodStore").attr("checked", true);
					jQuery("#shippingAddressBlockContainer").hide();
					jQuery("#storePickupContainer").slideDown();
				}
			}
		} else {
			jQuery("#paymentMethod0").attr("disabled", false); //Re-enable it
		}
	}
	/****************************************************************************************/
	
	
	
	/****************************************************************************************/
	/*Show the shipping address form (or not)												*/
	/****************************************************************************************/	
	jQuery("#shippingSameAsBilling").click(function(){
		if(jQuery(this).is(":checked")){
			jQuery("#shippingAddressContainer").hide();
		} else {
			jQuery("#shippingAddressContainer").slideDown();
		}
	});
	/****************************************************************************************/	
	


	/****************************************************************************************/
	/*Cancel installation																	*/
	/****************************************************************************************/
	jQuery("#clearInstall").click(function(){
		if(confirm('Voulez-vous vraiment annuler le rendez-vous d\'installation?')){
			$.ajax({
				url: "includes/forms/processCancelInstall.php",
				context: document.body,
				dataType: "json",
				data: {clientID: jQuery("#clientID").val()},
				type: "POST",
				success: function(){
					jQuery("td.scheduleDate").text("Non planifiée");
				}
			});
		}
	});
	/****************************************************************************************/		



	/****************************************************************************************/
	/*Validate the forms																	*/
	/****************************************************************************************/
	//This one is for the client picking for reps
	$("form#clientForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processPickClient.php",
		success:	function(){
			$("#clientAccount").attr("disabled", "true");
			$("#clientName").attr("disabled", "true");
			$("#neq").attr("disabled", "true");
			$("#dateFormed").attr("disabled", "true");
			$("#phoneNumber").attr("disabled", "true");
			$("#faxNumber").attr("disabled", "true");
			$("#adminContactName").attr("disabled", "true");
			$("#adminContactEmail").attr("disabled", "true");
			$("#pickClientSubmit").attr("disabled", "true");
		},
		failure: function() {}
	})
	
	//This one is for the install date scheduling
	$("form#installForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processInstallDate.php",
		success:	function(){
			jQuery("td.scheduleDate").text(jQuery("#installDate").val());
		},
		failure: function() {}
	})
	
	//This one is for scanning the modem serial numbers
	$("form#receiveForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processReception.php",
		success:	function(){
			window.location.href='lav.php';
		},
		failure: function() {}
	})
	
	//This one is to get the PAE code from email and info
	$("form#paeCodeForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "my/includes/forms/processPaeCode.php",
		success:	function(){
			$("#submitPaeCode").attr("disabled", true);
			$("#paeCodeSent").show();
		},
		failure: function() {}
	})
	
	//This one is for the addresses input for checkout
	$("form#shippingAndBilling").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processAddresses.php",
		success:	function(){
			window.location.href='caisse.php?doConfirm';
		},
		failure: function() {}
	})
	
	//This one is for the registration form
	$("form#registrationForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processRegistration.php",
		success: function(){
			//Todo - show a nice message
			$("#registrationSubmitButton").attr("disabled", true);
			$("#registrationSent").show();
		},
		failure: function(){}
	})
	
	//This one is the main login form - also checks if we should redirect out
	$("form#loginForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processLogin.php",
		success :  function() {
			var redirect = hasParam("cbURL");
			if(redirect == ""){
				window.location.href='portail.php';
			} else {
				window.location.href=unescape(redirect);
			}
		},
		failure : function() {}
	})
	
	//This one is the main login form - also checks if we should redirect out
	$("form#paeForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "my/includes/forms/paeForm.php",
		success :  function() {
			var code = $("#offerCode").val();
			var code = code.toUpperCase();
			window.location.href='http://www.proxitelecom.com/'+code;
		},
		failure : function() {}
	})
	
	//This one is the main login form (ON THE HOME PAGE) - also checks if we should redirect out
	$("form#loginFormHome").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "my/includes/forms/processLogin.php",
		success :  function() {
			var sID = $("#sID").val();
			window.location.href='http://monproxitelecom.com/portail.php?sID='+sID;
		},
		failure : function() {}
	})
	
	//This one is for the upgrades add to cart form
	$("form#upgradeForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processUpgrade.php",
		success :  function() {
			$.validationEngine.buildPrompt("#cartCount", $.validationEngine.settings.allrules['upgradeDone'].alertText+"<br />","pass");
			$("#subscriberNumber").val("");
			$("#subscriberName").val("");
			$("#subscriberEmail").val("");
			$("#notes").val("");
			var cartCount = $("#cartCount").html();
			var found = /[0-9]+/.exec(cartCount); //Ancien nombre dans le cart
			var str = "";
			if(found == null)
				str = "1 item"; //1 seul item dans le cart
			else{
				str = (parseInt(found[0]) + 1) + " items"; //+1 item dans le cart
			}
			$("#cartCount").html("<a href='panier.php'>"+str+"</a>");
			$.validationEngine.performScroll();
		},
		failure : function() {}
	})
	
	//This one is for the Fleet add to cart form
	$("form#fleetForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processFleet.php",
		success :  function() {
			$.validationEngine.buildPrompt("#cartCount", $.validationEngine.settings.allrules['fleetDone'].alertText+"<br />","pass");
			$("#directoryNumberRegion").val("");
			$("#ban").val("");
			$("#clientNumber").val("");
			var qty = $("#quantity").val();
			$("#quantity").val("1");
			$("#ratePlan").val("");
			var cartCount = $("#cartCount").html();
			var found = /[0-9]+/.exec(cartCount); //Ancien nombre dans le cart
			var str = "";
			if(found == null){
				str = qty;
				if(parseInt(qty) > 1)
					str += " items"; //qty items dans le cart
				else
					str += " item";
			}else{
				str = (parseInt(found[0]) + parseInt(qty)) + " items"; //+qty item dans le cart
			}
			$("#cartCount").html("<a href='panier.php'>"+str+"</a>");
			$.validationEngine.performScroll();
		},
		failure : function() {}
	})
	
	//This one is for the activations add to cart form
	$("form#activationForm").validationEngine({
		ajaxSubmit: true,
		ajaxSubmitFile: "includes/forms/processActivation.php",
		success :  function() {
			$.validationEngine.buildPrompt("#cartCount", $.validationEngine.settings.allrules['activationDone'].alertText+"<br />","pass");
			//Now clear all fields here...
			$("#subscriberName").val("");
			$("#subscriberNumber").val("");
			$("#subscriberEmail").val("");
			$("#portedDirectoryNumber").val("");
			$("#portedCarrier").val("");
			$("#portedSerial").val("");
			$("#portedAccountNumber").val("");
			$("#directoryNumberRegion").val("");
			$("#ratePlan").val("");
			$("#features").val("");
			var cartCount = $("#cartCount").html();
			var found = /[0-9]+/.exec(cartCount); //Ancien nombre dans le cart
			var str = "";
			if(found == null)
				str = "1 item"; //1 seul item dans le cart
			else{
				str = (parseInt(found[0]) + 1) + " items"; //+1 item dans le cart
			}
			$("#cartCount").html("<a href='panier.php'>"+str+"</a>");
			$.validationEngine.performScroll();
		},
		failure : function() {}
	})
	
	//For PAE orders
	$("form#pae-order").validationEngine();
	/****************************************************************************************/
	
		
	
	/****************************************************************************************/
	/*Check for specified parameter and return the rest of the query string if present.		*/
	/****************************************************************************************/
	function hasParam(name){
		var str = window.location.href;
		var occurrence = str.search(name);
		if(occurrence == -1){
			return "";
		} else {
			return str.substr(occurrence+6); //Le 6 c'est length() de name + 1 (dans le cas de cbURL)
		}
	}
	/****************************************************************************************/
	
	
	
	/****************************************************************************************/
	/*Make rows clickable in grid tables with links											*/
	/****************************************************************************************/
	$("tr.clickable").hover(function(){
		$(this).toggleClass("hoverClickable");
	});
	
	$('tr.clickable').click(function(){
		window.location.href = $(this).find('td a').attr('href');
	});
	/****************************************************************************************/
	
	
	
	/****************************************************************************************/
	/*Replace the submit button by a nice image												*/
	/****************************************************************************************/
	$("#submitButtonAjax").click(function(){
		$("#ajaxLoaderDiv").hide();
		$("#ajaxLoaderDiv").before('<div id="loader"><img src="http://www.proxitelecom.com/includes/images/ajax-loader.gif"/></div>');
	});
	/****************************************************************************************/
	
});

