var unknownError = "We're sorry.Your request could not be processed.  Please try again later.";
/*--------Pop Up-------------------------*/
var xcPopUp = function(el){ 
	$(el).unbind('click').click(function(e){
			// Remove any previous instances of the layer
			$('#tempWrap').remove();
			$('#tempContent').remove();
			// This is the layer wrap
			var templayer = '<div id="tempWrap" class="layerWrap"></div> \
							 <div id="tempContent" class="layerContent"> \
								<a class="closeWin" title="Close" href="javascript:;">close</a> \
								<p class="layerBody"></p> \
							 </div>';
			$('body').append(templayer);
			
			var xcPop=  "<html lang='en'>"+
							"<head><title>Express Checkout Instant Purchase</title></head>"+
							"<body><div id='xcWhatsThisContent'><h2>Express Checkout lets you instantly purchase a single item.</h2>"+
							"<p>You will be automatically charged (including shipping method) and the item will be shipped to your Express Checkout address.</p>"+
							"<a href='javascript:validateUserLogin();'>Manage your Express Checkout settings.</a></div></body></html>";

			// Load in the dynamic page for the popup
			$('#tempContent p.layerBody').append(xcPop);
				// Set the wrapper height
				var preAnimateHeight = $('.layerContent').height();
				//$('.layerWrap').height(preAnimateHeight + 10);
				$('.layerWrap').css('height', (preAnimateHeight + 10) + "px");
				// Show the layer
				$('#tempWrap').show().css('top', e.pageY).css('left', (e.pageX - 310));
				$('#tempContent').show().css('top', (e.pageY + 5)).css('left', (e.pageX - 305));			
				$('a.closeWin').click(function(){
					$('#tempWrap').remove();
					$('#tempContent').remove();
				});
			
			});
}

/*----Count down timer set for 5 mins ----*/
var running = false;
var endTime = null;
var timerID = null;
//setting the timer start
var timeAmount = 5000;

function startTimer() {
    running = true
    now = new Date();
    now = now.getTime();
    endTime = now + (timeAmount * 60 * 1);
    showCountDown();
}

function showCountDown() {
    var now = new Date();
    now = now.getTime();
    if (endTime - now <= 0) {
        stopTimer();
        $('a.verifyConfirm_cnclOrder').html('<img src="'+imagePath+'img/btn/btn_cnclOrder_inactive.gif" alt="Undo your order" width="100px" height="20px">').css('cursor','default');
        $('a.verifyConfirm_cnclOrder').unbind('click').click( function() {
            return false; 
        });
    } else {
        var count = new Date(endTime - now);
        var theMin = count.getMinutes();
        var theSec = count.getSeconds();
        var theTime = theMin;
        theTime += ((theSec < 10) ? ":0" : ":") + theSec
        $('input#timerDisplay').val( theTime );
        if (running) {
            timerID = setTimeout("showCountDown()",1000);
        }
    }
}

function stopTimer() {
    clearTimeout(timerID);
    running = false;
}

/* ---- To hide Order Confirm and display cancellation confirmation-----*/
var xcCancel = function(el) {
    $(el).click(
	function() {
        stopTimer();
        ajaxCallForCancel();
    });
}
function ajaxCallForCancel() {

	var orderId ;
	var storeId ;
	var catalogId ;
	var ordPaymentType;
	
	if(document.ThankYouForm.orderId){
		orderId = document.ThankYouForm.orderId.value;
	}
	if(document.ThankYouForm.storeId){
		 storeId = document.ThankYouForm.storeId.value;
	}
	if(document.ThankYouForm.catalogId){
		 catalogId = document.ThankYouForm.catalogId.value;
	}
	if(document.ThankYouForm.ordPaymentType){
		 ordPaymentType = document.ThankYouForm.ordPaymentType.value;
	}
	
	var checkoutURL = 'OrderCancellation?';
	if(ssoFlag =='ON') {
		checkoutURL = '/shc/s/OrderCancellation?';
	}
	checkoutURL = checkoutURL + "storeId=" + storeId ;
	checkoutURL = checkoutURL + "&orderId=" + orderId;
	checkoutURL = checkoutURL + "&catalogId=" + catalogId;
	checkoutURL = checkoutURL + "&ordPaymentType=" + ordPaymentType;
	
	
	$.ajax({
		type: "POST",
		url: checkoutURL,
		dataType: "html",
		data: {},
		cache: false,
		success: function(responseHtml, textStatus){
			$('#orderCancellAjaxResponse').html(responseHtml);  // set the ajax response to innerHtml
			var status = false;
			if (document.getElementById("orderCancellationStatus")){
							status = eval(document.getElementById("orderCancellationStatus").value);
							
			}
			if (status) {
				 $('div#xcOrderCancelled').show();
				 $('h2#orderReceived, div#verifyConfirmWrapper').hide(); 
			} else {
			
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
						
			var errDiv = document.getElementById("errorMsg");
			getObjectInnerTextUserReg(errDiv, unknownError);  
		}
	});
	
		

}

/*the loading gif*/
function loadingAnimation() {
	var height = $(window).height();
	var width = $(window).width();
    $('div#loadingAnimation').css('width', width ).css('height', height );
}

$(document).ready(function(){
    startTimer();
    /*---cancled confirmation is hidden---*/
    $('div#xcOrderCancelled').hide();
    xcCancel('a.verifyConfirm_cnclOrder');
    /*----Pop Up Call for Product Page What's This Express Checkout--*/
    xcPopUp('div#productXC p')
    /*------loading gif------*/
    loadingAnimation();
});

function validateUserLogin(){   
    	
	var validateLoginUrl="ValidateLoginViewHttps?langId=-1&storeId="+storeIdReq+"&catalogId="+catalogId;
	//var a=$.getJSON(validateLoginUrl,reDirectToMyProfile);
	$.ajax({
	   type: "GET",
	   dataType:"json",
	   url: validateLoginUrl,
	   success: reDirectToMyProfile,
	   timeout:2000
	   });
	  //ajaxCall(validateLoginUrl,'reDirectToMyProfile');
}

function reDirectToMyProfile(responseVal){ 
	 
    userTypeForXC=responseVal.loginValue;
    
	if(typeof userTypeForXC != 'undefined' && userTypeForXC == 'R'){
		var xCUrlForMyprofile= "UserAccountView?catalogId="+catalogId+"&storeId="+storeIdReq;
		window.location = xCUrlForMyprofile;
	}else{
		var xCUrlForLogin = "LogonForm?langId=-1&storeId="+storeIdReq+"&catalogId="+catalogId;
		window.location = xCUrlForLogin;
	}
}

