$(document).ready( function(){
    checkDomestic();
	
	this.$form = $('#ctcForm');
        
	// Display bubble
	$('#ctcForm').bind('mouseenter', function() { $('#ctcForm').find('#ctcBubble').removeClass('hide'); });
	$('#ctcForm').bind('mouseleave', function() { $('#ctcForm').find('#ctcBubble').addClass('hide'); });
	
	// Replace png with gif if IE6
	if(window.attachEvent) 
	{ 
		 $('#ctcForm').find('#ctcBubble').attr('src', '/images/general/ctc-helper.gif');
	}
	
    $('#ctcForm .submitButton').bind("click", function(e){
        e.preventDefault();
        e.stopImmediatePropagation();
        do_dsdial();
    });
    
});


ET.CTC = {
	customerID:  (new Date()).getTime()
}


var callinprogress = 0;
//var myDomain = "fcl-wcs";
var currentDomain = window.location.hostname;
var myDomain = currentDomain;
var isDomesticFlightProduct = false;

function checkDomestic(){   
    
    if($("#domesticCtc").length){
        isDomesticFlightProduct = true;
    }     
    if(isDomesticFlightProduct == true){        
        $('#leftColumn #ctcForm').remove();
    }
    
}

function setPlidForState() {  
    var postcode = ($("#pcode").length > 0) ? $("#pcode").val() : 'xxxx';
	var statePrefix = postcode.charAt(0);
	var statePlid = "";
    var defaultPlid = $("#plid").val();
    var hasPcode = ($('#pcode').length)?true:false;    
    
    if(defaultPlid.length > 0 && hasPcode.length == 0 || !hasPcode){
        statePlid = defaultPlid;
    }else{
        switch (statePrefix) {
		case "0"://NSW, ACT, NT
			statePlid = "wZwbHe4";
			break;
		case "1"://NSW, ACT, NT
			statePlid = "wZwbHe4";
			break;
		case "2"://NSW, ACT, NT
			statePlid = "wZwbHe4";
			break;
		case "3"://VIC, TAS
			statePlid = "xsPsE2";
			break;
		case "4":// QLD
			statePlid = "jLkUqJ";
			break;
		case "5"://SA
			statePlid = "4CXB75X";
			break;
		case "6"://WA
			statePlid = "kk896R";
			break;
		case "7"://VIC, TAS
			statePlid = "xsPsE2";
			break;
		case "8"://NSW, ACT, NT
			statePlid = "wZwbHe4";
			break;
		case "9"://NSW, ACT, NT
			statePlid = "wZwbHe4";
			break;
		default:
			statePlid = "jLkUqJ";
			break;
        }
    }
    statePlid = (isDomesticFlightProduct)? "FeZd4z1" : statePlid;   
	document.getElementById('plid').value = statePlid;
}

function do_dsdial()
{

	// Record event in Google Analytics
	ET.registerGAPageView(
	{ 
		basePath: '/on-page-event/',
		path: 'click-to-call'
	});

	var zero_re =/^0/;
	var plus_re = /^\+/;
	var let_re = /\w/;
    var $myPhone = $('#ctcForm').find('#phone');
	var phone = $myPhone.val();
	var plid = document.getElementById("plid").value;
	//var myMsg = document.getElementById("hover_info");
    var myMsg = $("#hover_info");
	
	var myPcode = document.getElementById("pcode");
	var PCode = ($("#pcode").length > 0) ? $("#pcode").val() : 'xxxx';

	if (callinprogress == 1){
		//myMsg.innerHTML = '<span class="hghlghterr">Call in progress...</span>';
        myMsg.html('<span class="hghlghterr">Call in progress...</span>');
		return;
	}    
	phone = phone.replace(let_re,"");
	if (phone == ''){
		$myPhone.val('e.g. 07 3000 0000');
		return;
	}
    
	//check that area code is entered
	if (($myPhone.val().length >= 1) && ($myPhone.val().substring(0,1) != '0')) {
		//myMsg.innerHTML = '<span class="hghlghterr">Please enter your area code before your telephone number</span>';
        myMsg.html('<span class="hghlghterr">Please enter your area code before your telephone number</span>');
		return;
	}
	
	if(isDomesticFlightProduct == false){
		//check postcode validity
		if (document.getElementById("pcode").value == '') {
			document.getElementById("hover_info").innerHTML = '<span class="hghlghterr">Please enter your postcode</span>';
			return;
		}
		errorMsg = 'Australian postcodes are 3 or 4 digit numbers between 200-300\nor 800-9999.';
		// Postcode must contain 3 or 4 digits, and no characters.
		numberOfDigits = 0;
		for (i = 0; i < document.getElementById("pcode").value.length; i++) {
			digit = parseInt(document.getElementById("pcode").value.charAt(i));
			if (isNaN(digit)) {
				document.getElementById("hover_info").innerHTML = errorMsg;
				return;
			}
			numberOfDigits++;
		}
		if (numberOfDigits != 3 && numberOfDigits != 4) {
			document.getElementById("hover_info").innerHTML = errorMsg;
			return;
		}
	}
	
	setPlidForState();
	var plid = document.getElementById("plid").value;
    
	// Ok, we should do something with the country codes
	phone = phone.replace(zero_re,"");
	phone = phone.replace(/\s/g,"");
	var Ephone = phone;
	Ephone = Ephone.replace(plus_re,"%2B");

    ET.TRACKING.trackEvent = {
        'action': 'enquiry',
        'typeOfEnquiry': 'clicktocall'
    };
    ET.TRACKING.eventTracking();

	var myProto = document.location.protocol;
    
	var myUrl = myProto+'//'+myDomain+'/ptt/pt-dialer.cgi'
	var Query = 'PLID='+plid+'&wantxml=yes&cmd=call&aparty='+Ephone+'&pcode='+PCode;
	//myMsg.style.display='block'; 
	//myMsg.innerHTML = '<span class="hghlghterr">Connecting you now...</span>';
    //myMsg.html('<span class="hghlghterr">Connecting you now...</span>');
    changeMyMsg('<span class="hghlghterr">Connecting you now...</span>');
	CTCResetCookie("phone", Ephone);

	// CTC initial request tracking

	ef_event_type="transaction";
	ef_transaction_properties = "ev_phoneleadrequest=1&ev_transid="+ET.CTC.customerID;
	ef_segment = "";
	ef_search_segment = "";
	ef_userid="2887";
	ef_pixel_host="pixel.everesttech.net";
	effp();


	ajax(myUrl,Query,parse_results);

}

function changeMyMsg(msg){
    var myMsg = $("#hover_info");
    myMsg.css("display", "block");
    myMsg.html(msg);
}

function parse_results(xmlDoc)
{
	//var myMsg = document.getElementById("hover_info");
    //var myMsg = $(".hover_info-text");
	
	try {
        var rc = xmlDoc.getElementsByTagName('rc').item(0).firstChild.data;
	}
	catch(err){
        //myMsg.style.display='block'; 
        
		//myMsg.innerHTML = '<span class="hghlghterr">Sorry, your local Flight Centre store is now closed! Please call between 9am-5pm Mon-Fri.</span>'; <!--temporary problem speaking with the server -->
        changeMyMsg('<span class="hghlghterr">Sorry, your local Flight Centre store is now closed! Please call between 9am-5pm Mon-Fri.</span>'); <!--temporary problem speaking with the server -->
		return;
	}
	if (rc != 1){
		var errmsg = $(xmlDoc).find('root errmsg').text();
		if (errmsg == 'no credit'){
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span>'+xmlDoc.getElementsByTagName('reason').item(0).firstChild.data+'</span>';
            changeMyMsg('<span>'+xmlDoc.getElementsByTagName('reason').item(0).firstChild.data+'</span>');
		}
		else if (errmsg == 'maximum free calls reached'){
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span>You have used all your free calls.<br>Please join to continue using Pep-Talk</span>';
            changeMyMsg('<span>You have used all your free calls.<br>Please join to continue using Pep-Talk</span>');
		}
		else if (errmsg == 'aparty number invalid') {
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span>The number you have entered is invalid. Please enter your full number including area code.</span>';
            changeMyMsg('<span>The number you have entered is invalid. Please enter your full number including area code.</span>');
		}
		else if (errmsg == 'out of hours') {
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span>Sorry, your local Flight Centre store is now closed! Please call between 9am-5pm Mon-Fri.</span>';
            changeMyMsg('<span>Sorry, your local Flight Centre store is now closed! Please call between 9am-5pm Mon-Fri.</span>');
		}
		else {
			//myMsg.innerHTML = '<span>'+errmsg+'</span>';
            changeMyMsg('<span>'+errmsg+'</span>');
		}
		callinprogress=0;
	}
	else {
		var status = '';
		try {
			status = xmlDoc.getElementsByTagName('status').item(0).firstChild.data;
			// status = 'call';
		}
		catch(err) {
			/* Call has probably termintated, hence no status for the ptid */
			callinprogress=0;
		}
		var ptid = xmlDoc.getElementsByTagName('ptid').item(0).firstChild.data;
		if (status == 'dialling'){
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span class="hghlghterr">Dialling...</span>';
			changeMyMsg('<span class="hghlghterr">Dialling...</span>');
            callinprogress=1;

		}
		else if (status == 'call'){
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span class="hghlghterr">Connected</span>';
            changeMyMsg('<span class="hghlghterr">Connected</span>');
           	jQuery('#ctcForm').append('<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1031823632/?label=ZSetCPakqgIQkMKB7AM&amp;guid=ON&amp;script=0"/>');

           	ef_event_type="transaction";
			ef_transaction_properties = "ev_phonelead=1&ev_transid="+ET.CTC.customerID;
			/*
			 * Do not modify below this line
			 */
			ef_segment = "";
			ef_search_segment = "";
			ef_userid="2887";
			ef_pixel_host="pixel.everesttech.net";
			effp();

			callinprogress=0;
		}
		else if (status == 'ready'){
			//myMsg.style.display='block'; 
			//myMsg.innerHTML = '<span class="hghlghterr">Ringing...</span>';
            changeMyMsg('<span class="hghlghterr">Ringing...</span>');
			callinprogress=1;
		}
		else if (status == 'failed'){
			var Reason = xmlDoc.getElementsByTagName('reason').item(0).firstChild.data;
			callinprogress=0;
			if (Reason == 'busy'){
				//myMsg.style.display='block'; 
				//myMsg.innerHTML = '<span class="hghlghterr">We were unable to reach you on the phone number provided.</span>';
                changeMyMsg('<span class="hghlghterr">We were unable to reach you on the phone number provided.</span>');
			}
			else if (Reason == 'busy-b'){
				//myMsg.style.display='block'; 
				//myMsg.innerHTML = '<span class="hghlghterr">Sorry, the consultant your call was directed to is currently busy, please try again in a moment.</span>';
                changeMyMsg('<span class="hghlghterr">Sorry, the consultant your call was directed to is currently busy, please try again in a moment.</span>');
			}
			else if (Reason == 'noanswer'){
				//myMsg.style.display='block'; 
				//myMsg.innerHTML = '<span class="hghlghterr">The phone number you provided rang out when we tried to connect, please check the number and try again.</span>';
                changeMyMsg('<span class="hghlghterr">The phone number you provided rang out when we tried to connect, please check the number and try again.</span>');
			}
			else if (Reason == 'noanswer-b'){
				//myMsg.style.display='block'; 
				//myMsg.innerHTML = '<span class="hghlghterr">Sorry, but your call was directed to a consultant that is unavailable. Please try again in a moment.</span>';
                changeMyMsg('<span class="hghlghterr">Sorry, but your call was directed to a consultant that is unavailable. Please try again in a moment.</span>');
                
			}
			else if (Reason == 'hangup'){
				//myMsg.style.display='block'; 
				//myMsg.innerHTML = '<span class="hghlghterr">The call was disconnected, please try again if you did not resolve your enquiry.</span>';
                changeMyMsg('<span class="hghlghterr">The call was disconnected, please try again if you did not resolve your enquiry.</span>');
			}
		}
		
		if ((status != 'call')&&(status != 'failed')&&(status !='')){
			var myProto = document.location.protocol;
			var myUrl = myProto+'//'+myDomain+'/ptt/pt-popoverlib.cgi';
			var Query = 'cmd=getstatus&ptid='+ptid;
			ajax(myUrl,Query,parse_results);
		}
	}
}

function ajax(url, vars, callbackFunction)
{


    var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");

	//alert(url+'?'+vars);

	request.open("POST", url, true);
	if (request.overrideMimeType){
		request.overrideMimeType('text/xml');
	}
	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 

	request.onreadystatechange = function(){

		if (request.readyState == 4 && request.status == 200) {
			var xmlDoc = request.responseXML;
			if (xmlDoc){
				//alert(request.responseText);
				callbackFunction(xmlDoc);
			}
		}
	}
	request.send(vars);

}

function URLencode (myString)
{
	var result = '';
	var x = 0;
	myString = myString.toString();
	var re = /(^[a-zA-Z0-9_.]*)/;
	while (x < myString.length){
		var match = re.exec(myString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			result += match[1];
			x += match[1].length;
		} else {
			if (myString[x] == ' '){
				result += '+';
			}
			else {
				var char = myString.charCodeAt(x);
				var val = char.toString(16);
				result += '%' + ( val.length < 2 ? '0' : '' ) + val.toUpperCase();
			}
			x++;
		}
	}
	return result;
}
function do_rollover()
 {
    document.getElementById('hover_info').style.display = 'block';
    //	document.getElementById('butimg').src='http://pep-talk.com.au/images/gui/icon_btn_call_on.png';
    //       document.getElementById('butdiv').style.backgroundImage='url(http://pep-talk.com.au/images/gui/icon_btn_text_on.png)';
}
function do_rollback()
 {
    document.getElementById('hover_info').style.display = 'block';
    //	document.getElementById('butimg').src='http://pep-talk.com.au/images/gui/icon_btn_call.png';
    //       document.getElementById('butdiv').style.backgroundImage='url(http://pep-talk.com.au/images/gui/icon_btn_text.png)';
}

function CTCResetCookie(cookieName, cookieValue) {
	if (CTCReadCookie(cookieName)) {
		CTCEraseCookie(cookieName);
		CTCSetCookie(cookieName, cookieValue);
	}
}
 
function CTCSetCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function CTCReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	    var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
	    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function CTCEraseCookie(name) {
    CTCSetCookie(name,"",-1);
}



// Submit form if enter key is pressed
function getKeyCode(x) {
		var charfield;
		if (x==1) {
			charfield=document.getElementById("phone");
		} else if (x==2) {
			charfield=document.getElementById("pcode");
		}
		charfield.onkeydown=function(e)	{
			var e=window.event || e
			if (e.keyCode==13) {
				do_dsdial();
			}
		}
	}
