// JavaScript Document

var objFocused="#textfield";

$(document).ready(function() {

	//initFB();

	try
  	{
		$(".fb-fan").colorbox({iframe:true, innerWidth:465, innerHeight:570});
		/*$(".fb-fan").fancybox({
			'padding'			: 0,
			'width'				: 480,
			'height'			: 580,
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titleShow'			: false,
			'type'				: 'iframe'
			});*/


	} catch(err) {}

	try
  	{
		$("#recommend-a-deal").fancybox({
			'padding'			: 0,
			'width'				: 600,
			'height'			: 460,
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titleShow'			: false,
			'type'				: 'iframe'
		});
	} catch(err) {}
	
	try
  	{
		$(".round-corner").corner();
	} catch(err) {}
	
	/*try
  	{
		$("#profile").hide();
	} catch(err) {}*/
	
	$fractionToAdd=0;
	if((jQuery.browser.version<8 && $.browser.msie) && $(".colorbox-if").attr("no-fraction")=="") $fractionToAdd=35;

	try
  	{
		$(".colorbox-if").colorbox({opacity:.60, iframe:true, innerWidth: parseInt($(".colorbox-if").attr("rel-width")) + $fractionToAdd, innerHeight: parseInt($(".colorbox-if").attr("rel-height")) + $fractionToAdd});
		/*$(".colorbox-if").fancybox({
			'padding'			: 0,
			'width'				: parseInt($(this).attr("rel-width")),
			'height'			: parseInt($(this).attr("rel-height")),
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titleShow'			: false,
			'type'				: 'iframe'
		});*/
	} catch(err) {}

	try
  	{
		$(".colorbox-if-auto").colorbox({opacity:.60, iframe:true, innerWidth: parseInt($(".colorbox-if-auto").attr("rel-width")) + $fractionToAdd, innerHeight: parseInt($(".colorbox-if-auto").attr("rel-height")) + $fractionToAdd, open:true});
	} catch(err) {}

	if($(".jq-dialog #autoopen").val()=="false") _autoOpen=false;
	else _autoOpen=true;

	try
  	{
		modalWidth=$(".jq-dialog #width").val();
		$(".jq-dialog").dialog({
			autoOpen: _autoOpen,
			width: modalWidth + 'px',
			modal: false
		});
	} catch(err) {}
	
	try
  	{
		$(".jq-error-dialog").dialog({
			autoOpen: true,
			width: 300,
			modal: true
		});
	} catch(err) {}
	
	try
  	{
		$('.open-jq-dialog').click(function() {
				$('.jq-dialog').dialog('open');
		});
	} catch(err) {}
	
	
	try
  	{
		$(".jq-dialog #close").click(function(){
			$(".jq-dialog").dialog("close");
		});
	} catch(err) {}
	
	try
  	{
		$(".formerror").dialog({
			width:500,
			modal: true
		});
	} catch(err) {}
	
	
	try
  	{
		$(".formerror-manual").dialog({
			autoOpen:false,
			width:500,
			height:200,
			modal: true,
			close: function() {
				$(objFocused).focus();
			}
		});
	} catch(err) {}
	
				
	try
  	{
		$('ul.expander li').expander({
		  slicePoint: 50, 
		  widow: 2,
		  expandEffect: 'fadeIn', 
		  userCollapseText: '[^]'
		});
	} catch(err) {}
	
	
});

function subscriptionBoxClose()
{
	hide('img-arrow');slideUp('subscription-box');
	$.ajax({
		type:"get",
		url: basePath+"/deal/show/subscriptionboxhide",
		success:function()
		{	
		}
	});
}

//'#textfield',-1,false,'Top: Get Daily Alerts'
function mailinglist(email_field_name,city_id,openinparent,source)
{

        if($('#error-message').hasClass('error-green')){
            $("#error-message").removeClass('error-green');
            $("#error-message").addClass('error');
        }
	if(openinparent==undefined) openinparent=false;
	if(source==undefined) source="";
	($(email_field_name).removeClass('error-box'));
	
	if(city_id==-1)
		city_id="/0";
	else
		city_id="/"+city_id;	
		
	var urlToAjax=basePath+"/mailinglist/index/subscribe/"+$(email_field_name).val()+city_id+'/openinparent/' + openinparent + '/source/' + source;
	
	$.ajax({
		type:"get",
		url: urlToAjax,		
		success:function(data)
		{	
			//alert(data);
			
			switch(data) 
			{			
			case "0":	
				
				mailing_list_error(email_field_name,'Please specify a valid email address.');
				break;
			case "1":
				//alert(openinparent + ":Thankyou you have been suceefully subscriber for our mailing list");
				if(openinparent==false) 
				{
					//if(field=="#mailinglist_email2" && message=="This email address is already on the mailing list!")
                                        if(email_field_name=="#mailinglist_email2" || email_field_name=="#mailinglist_email_iphone" )
					{
						location.href=basePath+"/static/page/iphone/subscribe/true";
					}
					else if(email_field_name=="#textfield"){
                                             $('#error-message').show();
                                             $("#error-message").removeClass('error');
                                             $("#error-message").addClass('error-green');
                                             $('#error-message #errors').html('<span >Your email has been added to the mailing list!</span>');
                                             $(email_field_name).val("");
                                        }
                                        else{
                                            parent.location.href=basePath+"/static/page/howitworks/subscribe";
                                        }
				}
				else 
				{
					//Set_Cookie('subscribed_tracking', 'true', 1, '/' );
					$('#div-signupform').hide();
					$('#div-successmessage').show();
					
					//window.parent.location.reload();
					//window.parent
					//window.parent.$(".colorbox-if-auto").colorbox.close();	
				}
				break;
			case "-1":
				mailing_list_error(email_field_name,"This email address is already on the mailing list!");
				break;
			case "-2":
				mailing_list_error(email_field_name,"There was some error while subscribing please try later or contact the admin");
				break;
			case "-5":
				mailing_list_error(email_field_name,"The specified email address is not valid");
				break;
			}
		}	
		});



return false;

}

function mailing_list_error(field,message)
{
	$('#error-message').show();
	if((field=="#mailinglist_email2" || field=="#mailinglist_email_iphone") && message=="This email address is already on the mailing list!"){}
	else $(field).addClass('error-box');
	objFocused=field;
	$('#error-message #errors').html('<span class="errormessage">'+message+'</span>');
	
}

function toggleTopCities(visibilityHidden) {
	//visibilityHidden
	$('#top-subscription-box').slideUp('slow');
	if(visibilityHidden==undefined) visibilityHidden="auto";
	if(visibilityHidden=="up")	$('#cities-slider').slideUp("slow");
	else if(visibilityHidden=="down") $('#cities-slider').slideDown("slow");
	else
	{
		if(jQuery.browser.version<8 && $.browser.msie)
		{
			if($('#subscription-box').is(':visible')) hide('img-arrow');
		}
		
		$('#cities-slider').slideToggle("slow", function() {
			if(jQuery.browser.version<8 && $.browser.msie)
			{
				if($('#subscription-box').is(':visible')) show('img-arrow');
			}
		 });
	}
	//if($('img-arrow'))
} 

function toggleTopSubscriptionBox(visibilityHidden) {
	//visibilityHidden
	$('#cities-slider').slideUp('slow');
	if(visibilityHidden==undefined) visibilityHidden="auto";
	if(visibilityHidden=="up")	$('#top-subscription-box').slideUp("slow");
	else if(visibilityHidden=="down") $('#top-subscription-box').slideDown("slow");
	else $('#top-subscription-box').slideToggle("slow");
} 
    function changeImagePath(id, toImageID) {
	$('#' + toImageID).attr("src", $("#" + id).attr("src"));
    }
    function changeImagePath2(id, toImageID, xsrc) {
	$('#' + toImageID).attr("src", basePath + "/application_data/images/nloading.gif");
	$('#' + toImageID).attr("src", xsrc);
    }
    function forceNumber(event){
	var keyCode = event.keyCode ? event.keyCode : event.charCode;
	if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 37 && keyCode != 39 && keyCode != 46 && keyCode != 116){
            return false;
        }
        return true;
    }
    function showbuyform(objVal){
	if(objVal == "express"){
		$("#card-payment-options").hide();
		$("#paypal").show();
	} else {
		$("#card-payment-options").show();
		$("#paypal").hide();
	}
    }
    function updateGrandTotal()
    {
	document.getElementById('deal_quantity').value=document.getElementById('deal_quantity_select').value;
	var unitprice= document.getElementById('deal_amount').value;
	var quantity= document.getElementById('deal_quantity').value;
        var hd_couponccode= document.getElementById('hdcouponconde').value;
	var grandtotal = quantity * unitprice;
        var coupon_discount = unitprice * quantity * hd_couponccode/100;
        var grandtotal2 = 0;
	document.getElementById('grandtotal').innerHTML = roundX(grandtotal);
        if(document.getElementById('voucher_discount')) document.getElementById('voucher_discount').innerHTML = roundX(coupon_discount);
	if(document.getElementById("deal_cashinhand")){
		grandtotal2 = grandtotal - 	document.getElementById("deal_cashinhand").firstChild.nodeValue-coupon_discount;
		if(grandtotal2 < 0){
			grandtotal2 = 0;
		} else {
			grandtotal2 = roundX(grandtotal2)
		}
		document.getElementById('grandtotal2').innerHTML = grandtotal2;
		if(grandtotal2 > 0){
			//document.getElementById("payment-options").style.display = 'block';
			document.getElementById("payment-options-box").style.display = 'block';
		} else {
			//document.getElementById("payment-options").style.display = 'none';
			document.getElementById("payment-options-box").style.display = 'none';
		}
	} else {
                grandtotal2 = grandtotal - 	coupon_discount;
		if(grandtotal2 < 0){
			grandtotal2 = 0;
		} else {
			grandtotal2 = roundX(grandtotal2)
		}
		document.getElementById('grandtotal2').innerHTML = grandtotal2;
		if(grandtotal2 > 0){
			//document.getElementById("payment-options").style.display = 'block';
			document.getElementById("payment-options-box").style.display = 'block';
		} else {
			//document.getElementById("payment-options").style.display = 'none';
			document.getElementById("payment-options-box").style.display = 'none';
		}

//		document.frmPayment.deal_amount.value = grandtotal;
	}
    }
    function roundX(grandtotal2){
	grandtotal2 = grandtotal2 + "";
	if(grandtotal2.indexOf(".") > -1){
		var limitX = grandtotal2.split(".");
		if(limitX[1].length == 1){
			grandtotal2 = limitX[0] + "." + limitX[1] + "0";
		} else {
			grandtotal2 = limitX[0] + "." + limitX[1].substring(0,2);
		}
	}
	return grandtotal2;	
    }
    function slideUp(id) {
	$("#" + id).slideUp('slow');
    }
    function slideToggle(id) {
	$("#" + id).slideToggle('slow');
    }
    function show(id) {
	$("#" + id).show();
    }
    function hide(id) {
	$("#" + id).hide();
    }

function copy_to_clipboard(text)  
{  
     if(window.clipboardData)  
     {  
     	window.clipboardData.setData('text',text);
     	alert('The text is copied to your clipboard...');
     }  
     else  
     {  
     	alert('This browser does not support this feature. Please copy text manually.');
    }  
}  
function display_ct() {
	var days=Math.floor(window.start / 86400);
	var hours = Math.floor((window.start - (days * 86400 ))/3600);
	var minutes = Math.floor((window.start - (days * 86400 ) - (hours *3600 ))/60);
	var secs = Math.floor((window.start - (days * 86400 ) - (hours *3600 ) - (minutes*60)));
	$('#days').html(days<10? '0'+days: days);
	$('#hours').html(hours<10? '0'+hours: hours);
	$('#minutes').html(minutes<10? '0'+minutes: minutes);
	$('#seconds').html(secs<10? '0'+secs: secs);
	window.start= window.start- 1;
	if(days <= 0)
		$('#days').hide();
	tt=display_c(window.start);
}
function display_c(start){
	window.start = parseFloat(start);
	var end = 0; // change this to stop the counter at a higher value
	var refresh=1000; // Refresh rate in milli seconds
	if(window.start >= end ){
		mytime=setTimeout('display_ct()',refresh);
	} else {
		document.location.reload();
	}
}
function closeMe()
{
	$(".colorbox-if-auto").colorbox.close();	
}

function initFB() {
	try
  	{
		FB_RequireFeatures(
		["XFBML"],
		function()
		{
			FB.init("03504284a6f24f6e3aab73c99732c7d4", "xd_receiver.htm");
		});
	} catch(err) {}
}

function facebook_onlogin() {
	window.location.reload();
}

function openColorBox(id, width, height)
{
	$("#" + id).colorbox({opacity:.60, iframe:true, innerWidth: width, innerHeight: height});	
}


/*
	Set Subscription Cookiw
	
	@author: waheed
	@date: April 13, 2101
*/

function doSubscriptionCookie()
{
	subscriptionCookie=Get_Cookie('subscribed');
	if(subscriptionCookie!=null) Delete_Cookie('subscribed');
	Set_Cookie('subscribed', 'true', 90, '/' );
}

/* 
	Javascript Cookie Functions 
	
	@author: waheed
	@date: April 13, 2101

*/

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
        return null;
}
// this deletes the cookie when called
    function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
	( ( path ) ? ";path=" + path : "") +
	( ( domain ) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
    function facebook_onlogin() {
	window.location.reload();
    }
    var openDivID="";
    function togglePaymentMode(control)
    {
	if(control.id=="paymentmode-CreditCard") {
            $('#payment-details').show();
	} else if(control.id=="paymentmode-Solo") {
            $('#payment-details').show();
	} else if(control.id=="paymentmode-Amex") {
            $('#payment-details').show();
	} else if(control.id=="paymentmode-Paypal") {
            $('#cc_fname').val("");
            $('#cc_lname').val("");
            $('#cc_address').val("");
            $('#cc_postcode').val("");
            $('#cc_city').val("");
            $('#payment-details').hide();
	}
	if(openDivID != "" && openDivID!=control.id && openDivID != "paymentmode-Paypal")
	{
            $('#div-' + openDivID).slideUp("slow", function ()
            {
                openDivID=control.id;
            });
	} else {
            openDivID=control.id;
	}
	$('#div-' + control.id).fadeIn("slow");
    }
    function nextbox(control)
    {
	if ($('#paymentmode-Amex').is(':checked')) {
            if(control.id=="cc_no" && $('#div-paymentmode-Amex #' + control.id).val().length==4) $('#div-paymentmode-Amex #cc_no4').focus();
            else if(control.id=="cc_no4" && $('#div-paymentmode-Amex #' + control.id).val().length==6) $('#div-paymentmode-Amex #cc_no1').focus();
	} else {
            var paymentModeId="CreditCard";
            if ($('#paymentmode-Solo').is(':checked')) paymentModeId="Solo";
            if(control.id=="cc_no" && $('#div-paymentmode-' + paymentModeId + ' #' + control.id).val().length==4) $('#div-paymentmode-' + paymentModeId + ' #cc_no1').focus();
            else if(control.id=="cc_no1" && $('#div-paymentmode-' + paymentModeId + ' #' + control.id).val().length==4) $('#div-paymentmode-' + paymentModeId + ' #cc_no2').focus();
            else if(control.id=="cc_no2" && $('#div-paymentmode-' + paymentModeId + ' #' + control.id).val().length==4) $('#div-paymentmode-' + paymentModeId + ' #cc_no3').focus();
	}
    }
    function next2box(obj, control, limit){
        if(obj.length == limit){
            $('#' + control).focus();
        }
    }