// jQuery Common functions

	function styleQuickContactForm() {
		
		$('#EnquiryAddForm label').hide();
		$('#EnquiryAddForm input[type="text"],.#EnquiryAddForm textarea').each(function(){
		
			var labelText = $(this).prev('label').text();
			
			if((this.value == labelText) || (this.value == '')) {//if the value of the input matches the labeltext
				this.value = labelText;
			}
		});	
			
		$('#EnquiryAddForm input[type="text"],#EnquiryAddForm textarea').addClass("idleField");
					
		$('#EnquiryAddForm input[type="text"],#EnquiryAddForm textarea').focus(function() {
			$(this).removeClass("idleField").addClass("focusField");
					
			if((this.value == $(this).prev('label').text())) {//if the value of the input matches the labeltext
				this.value = '';
			}
			
		});		
		$('#EnquiryAddForm input[type="text"],#EnquiryAddForm textarea').blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
			
			if((this.value == '')) {//if the value of the input matches the labeltext
				this.value = $(this).prev('label').text();
			}			
		});
	}
	
	function styleAweberForm() {
		
		$('#aweberForm label').hide();
		$('#aweberForm input[type="text"]').each(function(){
		
			var labelText = $(this).prev('label').text();
			
			if((this.value == labelText) || (this.value == '')) {//if the value of the input matches the labeltext
				this.value = labelText;
			}
			
		});
				
		$('#aweberForm input[type="text"]').addClass("idleField");
	
		$('#aweberForm input[type="text"]').focus(function() {
			$(this).removeClass("idleField").addClass("focusField");
					
			if((this.value == $(this).prev('label').text()) || ($(this).hasClass("error-text"))) {//if the value of the input matches the labeltext
				$(this).removeClass("error-text");
				this.value = '';
			}
			
		});		
		$('#aweberForm input[type="text"]').blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
			
			if((this.value == '')) {//if the value of the input matches the labeltext
				this.value = $(this).prev('label').text();
			}
			
		});
	}
	
	function styleReferralForm() {
		
		//alert('styling');
		$('#ReferralAddForm label').hide();
		$('#ReferralAddForm input[type="text"],#ReferralAddForm textarea').each(function(){
		
			//var labelText = $(this).prev('label').text();
			
			//if((this.value == labelText) || (this.value == '')) {//if the value of the input matches the labeltext
			//	this.value = labelText;
			//}
			
			//error messages
			//if(($(this).next('div.error-message').length)&&(this.value == '')){
				//$(this).next('div.error-message').hide().text();
				//$(this).removeClass('form-error');
				
				//$(this).addClass('error-text');
			//}
		});
				
		$('#ReferralAddForm input[type="text"],#ReferralAddForm textarea').addClass("idleField");
	
		$('#ReferralAddForm input[type="text"],#ReferralAddForm textarea').focus(function() {
			$(this).removeClass("idleField").addClass("focusField");
					
			if((this.value == $(this).prev('label').text()) || ($(this).hasClass("error-text"))) {//if the value of the input matches the labeltext
				$(this).removeClass("error-text");
				this.value = '';
			}
			
		});		
		$('#ReferralAddForm input[type="text"],#ReferralAddForm textarea').blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
			
			//if((this.value == '')) {//if the value of the input matches the labeltext
			//	this.value = $(this).prev('label').text();
			//}
			
		});
	}	
		
	function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
	}

	
	
	//checks for default values of form on submit to prevent them being submitted	
	function checkValues(){
		
		$('input[type="text"],textarea').each(function(){
												 
			//alert('match');
	
			if( ($(this).val() == $(this).prev('label').text()) || ($(this).val() == $(this).next('div.error-message').text()) ){
				$(this).val("");
			}
		});		
	}
	
	function ebookSubmitValidation() {

		$('#aweberForm').submit(function(event){
			//check email field and set error message
			var errorMessage = '';
			//is it filled in and is it valid?
			var emailAddress = $('#from').val();
			if(!isValidEmailAddress(emailAddress)){
				errorMessage = 'Emailアドレスをご確認ください';
				//set error class
				$('#from').addClass('error-text').val(errorMessage);
				//stop submit
				return false;
			}
			//alert(errorMessage);
			//return false;
		
		
		});
											   
	}
	
	function ajaxSubmitQuickContactForm() {
		//triggered when contact form is submitted
		$('form.quickcontact').submit(function(){
			//alert('submit');
			//check default values and blank them if required.
			checkValues();
			
			//alert('ajax time');
			//do ajax post
			$.ajax({
				type: "POST",
				url: "/enquiries/add/",
				data: $(this).serialize(),
				success: function(html,data){
					//alert(html);
					$(".quickcontactDisplay").html(html).css({ opacity: 0 }).fadeTo(500,1);
					styleQuickContactForm();
					ajaxSubmitQuickContactForm();
					//alert(data);
				}
			});			
			return false;
		});
	}
	
	function ajaxSubmitEmailForm() {
		//triggered when contact form is submitted
		$('#emailguide form, #emailguidedouble form').submit(function(){
			//alert('submit');
			//check default values and blank them if required.
			checkValues();
			
			//alert('ajax time');
			//do ajax post
			$.ajax({
				type: "POST",
				url: "/prospects/add/",
				data: $(this).serialize(),
				success: function(html,data){
					//alert(html);
					$(".emailguideDisplay").html(html).css({ opacity: 0 }).fadeTo(500,1);
					styleEmailForm();
					ajaxSubmitEmailForm();
					//alert(data);
				}
			});			
			return false;
		});
	}
	
	function ajaxSubmitReferralForm() {
		//triggered when contact form is submitted
		$('form#ReferralAddForm').submit(function(){
			//alert('submit');
			//check default values and blank them if required.
			checkValues();			
			//alert('ajax time');
			//do ajax post
			$.ajax({
				type: "POST",
				url: "/referrals/add/",
				data: $(this).serialize(),
				success: function(html,data){
					console.log(html);
					$("div.content").html(html);
					styleReferralForm();
					ajaxSubmitReferralForm();
					//alert(data);
				}
			});			
			return false;
		});
	}
	
	
	function popUp(URL){
		day = new Date();
		id = day.getTime();
		eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=520,height=470');");
	
		
	}
	
	function updateTariff(data){
	
		$('td.incoming'   ).html(data.incoming);
		$('td.national'   ).html(data.national);
		$('td.usacanada'  ).html(data.usacanada);					
		$('td.mobalphones').html(data.mobalphones);
		$('td.countries'  ).html(data.countries);
		$('td.sms'        ).html(data.sms);
		$('td.smsincoming').html(data.smsincoming);

		
	}
	
	function updateShipping(data){
		
		$('td.standard'  ).html(data.standard);
		$('td.standardOn').html(data.standardOn);
		$('td.priorityOn').html(data.priorityOn);
		$('td.satMorn'   ).html(data.satMorn);
	}
	
	function clearTariff(){
		
		$('td.incoming, td.national, td.usacanada, td.mobalphones, td.countries, td.sms, td.smsincoming').html('-');
	}
	
	function clearShipping(){
		
		$('td.standard, td.standardOn, td.priorityOn, td.satMorn').html('-');
	
	}
	
	function hideTabs(){
		if($('#greenmulti').length>0 ){$('#greenmulti').hide();}
		if($('#orangemulti').length>0){$('#orangemulti').hide();}
		if($('#purplemulti').length>0){$('#purplemulti').hide();}
		if($('#greymulti').length>0  ){$('#greymulti').hide();}
	}

	
	function showTabs(colour){
		$('#' + colour + 'multi').show();
	}
	
	function getColour(element){
		var classList = $(element).attr('class').split(/\s+/);
			if ($.inArray('green',classList) >=0) { return 'green'; }
			if ($.inArray('orange',classList)>=0) { return 'orange';}
			if ($.inArray('purple',classList)>=0) { return 'purple';}
			if ($.inArray('grey',classList)  >=0) { return 'grey';  }
	}
	
	

//start ---------------------------------------------------------------------------------------------

$(document).ready(function() {
						   
	//####################################  Buy Buttons START ##################################					   					   
	
	$('ul.buttons a').click(function(e){
		var linkClass = $(this).attr('class');
		if (linkClass){
			//default form submit using class from link
			e.preventDefault();			
			var checkbox = 'input.' + linkClass;
			if($(checkbox).length>0){
				//see if its checked
				if($(checkbox + ':checked').length > 0){
					//its checked
					var buyForm = $('form.'+ linkClass);
				}else{
					//not checked
					var buyForm = $('input.' + linkClass).parents('form:first');
				}
			}else{
				//doesnt exist
				var buyForm = $('form.'+ linkClass);
			}
			buyForm.submit();
		}
	});
	
	//####################################  Buy Buttons END ##################################	
	
	
	
	//####################################  Shipping Rates START ##################################
	
	//Shipping table for landing/product pages
	$('select.shipping').change(function(){	
		//$('.countryDropdown select').val($(this).val());
		//if($('p.message').length){ $('p.message').remove();}
		
		var selected = $(this).find("option:selected").html();
		//alert(selected);		
		if(selected != 'Select delivery location'){
		
		$.ajax({
				type: "GET",
				url: "/shipping/tariff/" + $(this).find("option:selected").html(),
				dataType: "json",
				success: function(data){
					updateShipping(data);
				}
		});
		}else{
			clearShipping();	
		}
	});
	
	//####################################  Shipping Rates END ##################################


	//####################################  List Expanders - START ##################################

	$('div.toggle').hide();
	$('ul.list li a, ul.mainlist li a').toggle(function(event){
		event.preventDefault();
		$(this).next('div').slideToggle(200);
   		$(this).contents('img.expander').attr('src','/img/site/lessbullet.jpg');
	},function(event) { // same here
		event.preventDefault();
		$(this).next('div').slideToggle(200);
   		$(this).contents('img.expander').attr('src','/img/site/morebullet.jpg');
    });			

	//####################################  List Expanders - END ##################################

	
	//####################################  Button Rollovers - START ##################################

	//Buy Button Rollovers
	$('.rollover').live('mouseover',
            function(){ // Change the input image's source when we "roll on"
                t = $(this);
				if(t.attr('src')!='/js/pngfix/blank.gif'){
					
                	t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1ol.$2"));
				}else{
					
					t.attr('style',t.attr('style').replace(/([\w-\.]+)(.png)/, "$1ol$2"));

					//alert(t.attr('style'));
					//FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='https://mobalcom.proteus.mobell.co.uk/img/site/bigbuttons/orangemoreinfo.png',sizingMethod='scale')"
					
				}
            });
	$('.rollover').live('mouseout',
            function(){ 
                t= $(this);
				if(t.attr('src') != '/js/pngfix/blank.gif'){
	                t.attr('src',t.attr('src').replace('ol',''));
				}else{
					
					t.attr('style',t.attr('style').replace('ol.png','.png'));


					//alert(t.attr('style'));
					
				}
            });
	
	//####################################  Button Rollovers - END ##################################
	
	
	//####################################  Form Button Rollovers - START ##################################

	//Buy Button Rollovers
	$('.formbutton').live('mouseover',
            function(){ 
			
			var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
			var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

					t=$(this);

				if($.browser.msie && (ie55 || ie6)) {
					// Change the input image's source when we "roll on"
					//alert('wax on' +  $(this).css('filter') + $(this).css('background-image') );
					//$(this).css({'backround-image':'none'});
					var filter = $(this).css('filter');
					//document.write(filter);
					$(this).css({"filter":filter.replace(/([\w-\.]+)(.png)/, "$1ol$2")});
					//alert('ive just set the new value to :'+ $(this).css('filter'));
				}else{
	                var background = $(this).css('background-image');
	               	t.css({"background-image":background.replace(/([\w-\.]+)(.png)/, "$1ol$2")});
	
				}
    });
	$('.formbutton').live('mouseout',
            function(){
				
				var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
				var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
				t=$(this);


				if($.browser.msie && (ie55 || ie6)) {
					var filter = $(this).css('filter');
					$(this).css({"filter":filter.replace('ol.png', '.png' )}); 
					//alert('wax off' + $(this).css('filter')  + $(this).css('background-image'));
				}else{
					var background = $(this).css('background-image');
	               	t.css({"background-image":background.replace('ol.png','.png')});
	
				}

            
    });
	
	//####################################  Form Button Rollovers - END ##################################

     
	 
	 //####################################  Tabbed Functionality - START ##################################
	
	
	//=====Main Tabs START=====

	$('li.one,li.two,li.three').click(function(){
		hideTabs();
		showTabs(getColour(this));
	});
	
	//=====Main Tabs END=====

	//=====Span links for Tabs START=====
	
	//use live() to bind event for all added spanlinks
	$('.showgreen').live('click',function(){
		hideTabs();
		showTabs('green');
	});
	
	$('.showorange').live('click',function(){
		hideTabs();
		showTabs('orange');
	});
	
	$('.showpurple').live('click',function(){
		hideTabs();
		showTabs('purple');
	});
	$('.showgrey').live('click',function(){
		hideTabs();
		showTabs('grey');
	});
	
	//=====Span links for Tabs START=====

	
	//####################################  Tabbed Functionality - END ##################################
	
	//####################################  Forms - START ##################################
	
	//apply all styles and effects to contact us form
	//contact page	
	if( $('#EnquiryAddForm').length ){
		styleQuickContactForm();
		ajaxSubmitQuickContactForm();
	}
	//referafriend form
	if( $('#ReferralAddForm').length ){
		styleReferralForm();
		$('#ReferralAddForm').submit(function(){
			checkValues();
		});
		//ajaxSubmitReferralForm();
	}
	
	
	
	//ebook signup box
	if( $('#aweberForm').length ){
		//style the form and add self-blanking input elements
		styleAweberForm();
		//add submit/validation functionality
		ebookSubmitValidation();
		
		$('img#ebooksubmit').hover(function(){
		 	$(this).css('cursor','pointer'); 
		});
		$('img#ebooksubmit').click(function(){
			$('#aweberForm').submit();
		});
	}

	//####################################  Forms - END ##################################
	
	
	//####################################  Aweber Ebook signup - START ##################################
	
	if( $('.iframe').length ){

		$('.iframe').fancybox({
			'frameWidth' : 500,
			'frameHeight': 400,
			'overlayShow': true
		});
	}
	
	
	//####################################  Aweber Ebook signup - END ##################################


	
});