//======================================================================
//================================ JCNB ================================
//======================================================================
//--------------------------------------------------------------------
//Global constant variables.
//--------------------------------------------------------------------
var homeURL = "http://www.justcarinsurance.com.au";
var mainWindowTarget = "_jcia_main";
var pdfWindowTarget = "_jcia_pdf";
var printWindowTarget = "_jcia_print";
var anniversaryQuoteTarget = "_jcia_annivquote";
var referToFriendTarget = "_jcia_refertofriend";
var windowNameToCheck = mainWindowTarget;
var pdfWindowObject = null; //Holds popup window for PDF printing
var callOnUnload = true; // used by script that opens a new window after closing the main one (eg anniversary quote)
var saveQuote = true; //used on the interim Quote schedule page, in the cancel button

//----------------------------------------------------------------------
//Clear any session currently attached to the current page.

//Dependency to other javascript function(s):
//- none
//----------------------------------------------------------------------
function clearSession() {
	var sessionId = "JSESSIONID";
	var cookie = document.cookie;

	if (cookie != null && cookie.indexOf(sessionId) >= 0) {
		document.cookie = sessionId + "=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}  

//----------------------------------------------------------------------
//Opens a new browser window to display JCI main application page.
//If window is already open new window will replace the existing window.

//Dependency to other javascript function(s):
//- "mainWindowTarget" constant variable
//----------------------------------------------------------------------
function openWindow(url) {
	var width = 975;
	var height = 700;
	var x = 0;
	var y = 0;

	if (screen.width > width + 10) { 
		x = (screen.width - width - 10) / 2;
	}

	if (screen.height > height) { 
		y = (screen.height - height) / 2;
	}

	w = window.open(url, mainWindowTarget, "toolbar=no,resizable=yes,dependent=no,scrollbars=yes,status=yes,width=" + width + ",height=" + height + ",left=" + x + ",top=" + y);
	w.focus();  
}

var mobileDevice;

function isMobile() {
	mobileStrings = new Array('Alcatel', 'Android', 'ACER', 'BlackBerry', 'IEMobile', 'HTC', 'iPhone', 'LG', 'MIDP', 'MOT', 'Nokia', 'Palm', 'SAMSUNG', 'Smartphone', 'SonyEricsson', 'Symbian', 'Windows CE', 'ZTE');
	ua = navigator.userAgent;

	for (i = 0; i < mobileStrings.length; i++) {
		if (ua.indexOf(mobileStrings[i]) > 0) {
			mobileDevice = mobileStrings[i];
			return true;
		}
	}

	return false;
}

function isiPad() {
	mobileStrings = new Array('iPad');
	ua = navigator.userAgent;

	for (i = 0; i < mobileStrings.length; i++) {
		if (ua.indexOf(mobileStrings[i]) > 0) {
			mobileDevice = mobileStrings[i];
			return true;
		}
	}
	return false;
}


var windowObjectReference = null;
function popupwindow(url) 
{
	var height = 650;
	var width = 1080;
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/3.2;
	var params = 'width='+width+', height='+height;
	params += ', top='+top+', left='+left;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=yes';
	params += ', resizable=yes';
	params += ', scrollbars=yes';
	params += ', status=yes';
	params += ', toolbar=yes';

	if (windowObjectReference == null || windowObjectReference.closed){
		windowObjectReference = window.open(url, 'windowName', params);
	} else {
		windowObjectReference.focus(); 
	}
}

function css(a){
	var sheets = document.styleSheets, o = {};
	for(var i in sheets) {
		var rules = sheets[i].rules || sheets[i].cssRules;
		for(var r in rules) {
			if(a.is(rules[r].selectorText)) {
				o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
			}
		}
	}
	return o;
}

function css2json(css){
	var s = {};
	if(!css) return s;
	if(css instanceof CSSStyleDeclaration) {
		for(var i in css) {
			if((css[i]).toLowerCase) {
				s[(css[i]).toLowerCase()] = (css[css[i]]);
			}
		}
	} else if(typeof css == "string") {
		css = css.split("; ");          
		for (var i in css) {
			var l = css[i].split(": ");
			s[l[0].toLowerCase()] = (l[1]);
		};
	}
	return s;
}

function popupCenter(pageURL,title,w,h) {
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
} 

/* ======================
   FORM functions - START 
   ====================== */
function isCancelPolicy(){
	return ($('#edit-submitted-type-of-enquiry').val() == "CANCEL");
}

function isAddressChange(){
	return ($('#edit-submitted-type-of-enquiry').val() == "ADDRESS_CHANGE");
}

function isIdValidationRequire(){
	var sEnquiryType = $('#edit-submitted-type-of-enquiry').val();
	switch(sEnquiryType){
		case "POLICY_CHANGE":
		case "ADDRESS_CHANGE":
		case "RENEW":
		case "REQUEST_DOCO":
		case "NEW_CLAIM":
		case "EXISTING_CLAIM":
		case "CANCEL":
			return true;
			break;
		default:				
			return false;
			break;
	}				
}

function setEnquiryTypeTexts(){
	var sEnquiryType = $('#edit-submitted-type-of-enquiry').val();
	switch(sEnquiryType){
		case "POLICY_CHANGE":
		case "ADDRESS_CHANGE":
			$('#webform-component-change-policy-enquiry').show();
			$('#webform-component-renew-policy-enquiry').hide();
			$('#webform-component-request-document-enquiry').hide();
			break;
		case "RENEW":
			$('#webform-component-change-policy-enquiry').hide();
			$('#webform-component-renew-policy-enquiry').show();
			$('#webform-component-request-document-enquiry').hide();
			break;
		case "REQUEST_DOCO":
			$('#webform-component-change-policy-enquiry').hide();
			$('#webform-component-renew-policy-enquiry').hide();
			$('#webform-component-request-document-enquiry').show();
			break;
		default:				
			$('#webform-component-change-policy-enquiry').hide();
			$('#webform-component-renew-policy-enquiry').hide();
			$('#webform-component-request-document-enquiry').hide();
			break;
	}
}

function setEnquiryTypeDetails() {
	var bIdValidationReq = isIdValidationRequire();
	var bCancelPolicy = isCancelPolicy();
	var bAddressChange = isAddressChange();
	setEnquiryTypeTexts();
			
	if (bIdValidationReq){
		$('#webform-component-id-validation-fields').show();
	} else {
		$('#webform-component-id-validation-fields').hide();
		resetDOB();
	}

	if (bCancelPolicy){
		$('#webform-component-cancel-details').show();
	} else {			
		resetCancelDetails();			
	}		
	
	if (bAddressChange){
		$('#webform-component-address-change').show();
	} else {
		resetAddressChange();
	}
	
	setIdValidationDetails();
}

function setIdValidationDetails() {		
	var bIdValidationReq = isIdValidationRequire();

	if(bIdValidationReq) {
		var option = $('#edit-submitted-id-validation-fields-option').val();
		switch(option){
			case "POLICY":
				$('#webform-component-id-validation-fields--policy-number').show();
				resetPhoneNumber();
				resetRego();
				resetAddress();
				break;
			case "PHONE":
				$('#webform-component-id-validation-fields--phone-number').show();
				resetPolicyNumber();
				resetRego();
				resetAddress();			
				break;
			case "REGO":
				$('#webform-component-id-validation-fields--rego').show();
				resetPolicyNumber();
				resetPhoneNumber();
				resetAddress();
				break;
			case "POSTAL":
				$('#webform-component-id-validation-fields--address-details').show();					
				resetPolicyNumber();
				resetPhoneNumber();
				resetRego();
				break;
			default:
				resetAddress();
				resetPolicyNumber();
				resetPhoneNumber();
				resetRego();
				break;
		}
	} else {
		$('#webform-component-id-validation-fields').hide();
		$('#edit-submitted-id-validation-fields-option').val("");
		resetAddress();
		resetPolicyNumber();
		resetPhoneNumber();
		resetRego();
	}
}
function resetDOB(){
	$('#edit-submitted-id-validation-fields-dob-day').val("");
	$('#edit-submitted-id-validation-fields-dob-month').val("");
	$('#edit-submitted-id-validation-fields-dob-year').val("");
}
function resetCancelDetails(){
	$('#webform-component-cancel-details').hide();
	$('#edit-submitted-cancel-details-date-day').val("");
	$('#edit-submitted-cancel-details-date-month').val("");
	$('#edit-submitted-cancel-details-date-year').val("");
	$('#webform-component-cancel-details--reason').val("");
}
function resetAddressChange(){
	$('#webform-component-address-change').hide();
	$('#edit-submitted-address-change-home-addr-previous').val("");
	$('#edit-submitted-address-change-home-addr-new').val("");
	
	$('#edit-submitted-address-change-postal-addr-previous').val("");
	$('#edit-submitted-address-change-postal-addr-new').val("");
	
	$('#edit-submitted-address-change-contact-details-home').val("");
	$('#edit-submitted-address-change-contact-details-mobile').val("");
	$('#edit-submitted-address-change-contact-details-business').val("");
}
function resetAddress(){
	$('#webform-component-id-validation-fields--address-details').hide();				
	$('#edit-submitted-id-validation-fields-address-details-address-line-1').val("");
	$('#edit-submitted-id-validation-fields-address-details-address-line-2').val("");
	$('#edit-submitted-id-validation-fields-address-details-postcode').val("");	
}
function resetPolicyNumber(){
	$('#webform-component-id-validation-fields--policy-number').hide();
	$('#edit-submitted-id-validation-fields-policy-number').val("");
}
function resetPhoneNumber(){
	$('#webform-component-id-validation-fields--phone-number').hide();
	$('#edit-submitted-id-validation-fields-phone-number').val("");
}
function resetRego(){
	$('#webform-component-id-validation-fields--rego').hide();
	$('#edit-submitted-id-validation-fields-rego').val("");
}
/* FORM functions - END */


$(document).ready(function() {
	/*
	if (isMobile() && (mobileDevice == "Android" || mobileDevice == "iPhone")) {
		alert("2"+mobileDevice);
		$(".menu a.level-1").each(function() {
			$(this).css("color", "red");
			var mobileOnClick; // this will be a function
			var mobileFirstClick = function() {
				mobileOnClick = mobileSecondClick;
				return false;
			};
			var mobileSecondClick = function() {
				mobileOnClick = mobileFirstClick;
				return true;
			};
			mobileOnClick = mobileFirstClick;
			$(this).bind("touchstart",function() {
				return mobileOnClick();
			});
		});
	}
	 */
	/*
	if (isMobile()) {
		console.log("is mobile! device: "+mobileDevice);
		$(".menu").click(function() {
			var object = css($(this));
			var output = '';
			for (property in object) {
			  output += property + ': ' + object[property]+'; ';
			}
			console.log(output);
			alert(output);
			$(this).attr("id","test-1010");
			alert(document.getElementById('test-1010').className);
			return false;
		});


	}
	 */
	if (isMobile() || isiPad()) {

		var menuLinks = $('.menu-name-primary-links a');

		$(menuLinks).each(function(){
			this.addEventListener('touchstart', function(){this.className = "hover";}, false);			
			this.addEventListener('touchend', function(){this.className = "";}, false);
		});
	}

	//RHS Quicklinks 
	$('.menu-name-menu-rhs-quicklinks ul.menu:first-child li.expanded ul.menu').css( "display","none" );
	$('.menu-name-menu-rhs-quicklinks ul.menu:first-child li.expanded ul.menu').hide(function(){
		$('.menu-name-menu-rhs-quicklinks ul.menu:first-child li.expanded').addClass('collapsed');
		$('.menu-name-menu-rhs-quicklinks ul.menu:first-child li.expanded').removeClass('expanded');


	});
	$('.menu-name-menu-rhs-quicklinks ul.menu:first-child li span').livequery('click', function() {
		var speed = 500;
		var clicked = this;
		if($(clicked).parent().hasClass('collapsed')){$(clicked).parent().removeClass('collapsed').addClass('expanded');}
		else if($(clicked).parent().hasClass('expanded')){$(clicked).parent().removeClass('expanded').addClass('collapsed');}
		$(clicked).parent().find("ul.menu").slideToggle(speed, function(){
			$(this).css({"height":"auto"});
		});
	});

	//Main Nav. Using Superfish Menu
	$("#nav-region ul.menu:first").superfish({ 
		delay:       100,                            // one second delay on mouseout 
		autoArrows:  false,                           // disable generation of arrow mark-up 
		dropShadows: false                            // disable drop shadows 
	});	

	$('nav#nav-region ul.menu li.expanded').each(function(){

		var item_width = $(this).outerWidth();
		var main = this;
		if($.browser.msie){
			$(main).find('ul.menu').css({ 'min-width': (item_width-17)+'px'});
		}else{
			$(main).find('ul.menu').css({ 'min-width': (item_width-45)+'px'});
		}

		$(main).find('ul.menu').css({ visibility: "", display: ""}); 
		$(main).find('ul.menu li').each(function(){
			var parent = $(this).parent().outerWidth();
			$(this).width(parent); //adjusts the widths of the li in the drop down to be equal for IE7		
		});
		$(main).find('ul.menu').css({ visibility: "hidden", display: "none" }); 


                jQuery("ul.menu > li").hover(function () {
                        var a = this.className.split("menu-mlid-")[1].split(" ")[0];
                        if (typeof ClickTaleExec=='function'){
                                ClickTaleExec("jQuery('li.menu-mlid-" + a + "').mouseover()");
                        }
                },
                function () {
                        var a = this.className.split("menu-mlid-")[1].split(" ")[0];
                        if (typeof ClickTaleExec=='function'){
                                ClickTaleExec("jQuery('li.menu-mlid-" + a + "').mouseout()");
                        }
                });


                 if (typeof ClickTaleContext == 'object') {        //expanding drop-down elements in A$
                        ClickTaleContext.getAggregationContextAsync("1", function(context){
                                $(".menu").css("visibility", "visible");
                                $(".menu").css("display", "block");

                        });
                 }

		
	});

	//>>>>>  FORM - START  <<<<<<
	/*
	$(".webform-datepicker").append('<input type="text" title="Open popup calendar" alt="Open popup calendar" class="webform-calendar webform-calendar-start-2011 webform-calendar-end-2012 webform-calendar-day-0 hasDatepicker" src="/sites/all/themes/jci/images/icon-calendar.png" id="webform-calendar-picker" style="position: absolute; border: medium none;">');
	try{console.log($('#webform-calendar-picker').val());} catch(e) {}

	$("#webform-calendar-picker").datepicker();
	//$("#webform-calendar-picker").click(function(e) { e.preventDefault(); });

	$("#webform-calendar-picker").change(function() {
		try{console.log($(this).val());} catch(e) {}
		$("form#webform-client-form-263 #edit-submitted-cancel-details-date-day").change();	
		$("form#webform-client-form-263 #edit-submitted-cancel-details-date-month").change();	
		$("form#webform-client-form-263 #edit-submitted-cancel-details-date-year").change();
	});
	 */

	// Require fields
	$("#edit-submitted-id-validation-fields-dob-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-option-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-cancel-details-reason-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-message-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-policy-number-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-phone-number-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-rego-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-address-details-address-line-1-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');
	$("#edit-submitted-id-validation-fields-address-details-postcode-wrapper label").append('<span class="form-required" title="This field is required.">*</span>');

	// Setup & Process conditional form fields
	setEnquiryTypeDetails();
	$('#edit-submitted-type-of-enquiry').change(setEnquiryTypeDetails);
	$('#edit-submitted-id-validation-fields-option').change(setIdValidationDetails);

	
	$("form#webform-client-form-263 #edit-submitted-state").customStyle();		
	$("form#webform-client-form-263 #edit-submitted-type-of-enquiry").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-id-validation-fields-option").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-id-validation-fields-dob-day").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-id-validation-fields-dob-month").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-id-validation-fields-dob-year").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-cancel-details-date-day").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-cancel-details-date-month").customStyle();	
	$("form#webform-client-form-263 #edit-submitted-cancel-details-date-year").customStyle();

	$('form#webform-client-form-263 .webform-datepicker input.webform-calendar').attr("src","/sites/all/themes/jci/images/icon-calendar.png");
	$('form#webform-client-form-263 div.form-item input').after('<span class="field-suffix"></span>').css({position:'absolute', border:'none'});

	$('ol li').wrapInner('<span class="standard"> </span>').addClass('red');

	// tooltip message class using TipTip jQuery Plugin + cancel the click event  
	$(".tooltip").tipTip({defaultPosition: "top", maxWidth: "auto"}).click(function(event){event.preventDefault(); });
	$(".tooltip-top").tipTip({defaultPosition: "top", maxWidth: "auto"}).click(function(event){event.preventDefault(); });
	$(".tooltip-bottom").tipTip({defaultPosition: "bottom", maxWidth: "auto"}).click(function(event){event.preventDefault(); });
	$(".tooltip-left").tipTip({defaultPosition: "left", maxWidth: "auto"}).click(function(event){event.preventDefault(); });
	$(".tooltip-right").tipTip({defaultPosition: "right", maxWidth: "auto"}).click(function(event){event.preventDefault(); });

	$('#webform-client-form-503').submit(function() {
		if (!$('#webform-client-form-503-results').is(":hidden")) {
			$('#webform-client-form-503-results').slideUp("fast");
		}
		var newsForm = $(this);
		$.ajax( {
			url: newsForm.attr( 'action' ) + "?ajax=true",
			type: newsForm.attr( 'method' ),
			data: newsForm.serialize(),
			success: function(response) {
			$('#webform-client-form-503-results').html($.trim(response));
			if ($('#webform-client-form-503-results').find("div.error").length > 0) {
				$('#webform-client-form-503 input#email-input').get(0).select();
				$('#webform-client-form-503 input#email-input').focus();
				$('#webform-client-form-503-results').slideDown("slow");
			} else {
				$('#webform-client-form-503 input#email-input').val('');
				$('#webform-client-form-503').slideUp('slow',
						function() { $('#webform-client-form-503-results').slideDown("slow");}
				);
			}

		}
		} );
		return false;
	});
	//>>>>>  FORM - END  <<<<<<

	// removing autocomplete for ios
	$('#edit-submitted-email, #email-input').attr("autocomplete","off").attr("autocorrect","off").attr("autocapitalize","off");


});


