function newuser() {
	$('#signin_menu').hide();
	$('#newuser_menu').show();
	$('#nusername').focus();
}

function existinguser() {
	$('#newuser_menu').hide();
	$('#signin_menu').show();
	$('#username').focus();
}

function registerNewUser() {
	$('.signin').click();
	newuser();
}

function editPersonalInfo() {
	$('#displayPersonalInfo').hide();
	$('#editPersonalInfo').show();
}

function closePersonalInfo() {
	$('#editPersonalInfo').hide();
	$('#displayPersonalInfo').show();
}

function editaddressdetails() {
	$('#displayaddressdetails').hide();
	$('#editaddressdetails').show();
}

function closeaddressdetails() {
	$('#editaddressdetails').hide();
	$('#displayaddressdetails').show();
}

function getRelativeUrl(partUrl){
	 if(location.href.indexOf("AxisBooks")!=-1){
		 return '/AxisBooks/' + partUrl;
	 }
	 else
		 return partUrl;
}

function toggleaccount() {	
	if($.mask.isLoaded(true))
		$.mask.close();
	else {
		$('#accountdiv').toggle();
		$('.accounttext a').css('color', '#D92524');
		 $('#account').expose({
			onClose : function(event){
				$('#accountdiv').toggle();
				$('.accounttext a').css('color', '#666666');				
			}
		});
	}
}

function signinclick() {
	_gaq.push(['_trackPageview', '/sigin']);
	var noCache = Date();
	var username = $('#username').val();
	var password = $('#password').val();
	
	$('#siginMessage').html(' ');
	var hasError = false;
	if(username == '') {
    	$('#siginMessage').html('Please enter email address.');
        hasError = true;
    }
	else if(password == '') {
    	$('#siginMessage').html('Please enter password.');
        hasError = true;
    }
	if(hasError == true) 
    	return false;

    $.getJSON(getRelativeUrl('login.html'), { username: username, password: password, 'noCache': noCache }, function(data){
		 if(data.result=="ok"){
			 location.href = getRelativeUrl('index.html');
		 }
		 else {
			 $('#siginMessage').html(data.result);		 
		 }			
	});
}

function registerCustomerclick() {
	var noCache = Date();
	var username = $('#nusername').val();
	var password = $('#npassword').val();
	var repassword = $('#nrepassword').val();
	
	$('#nsiginMessage').html(' ');
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    
    if(username == '') {
    	$('#nsiginMessage').html('Please enter email address.');
        hasError = true;
    }
    else if(!emailReg.test(username)) {
    	$('#nsiginMessage').html('Enter a valid email address.');
        hasError = true;
    }
    else if(password == '') {
    	$('#nsiginMessage').html('Please enter password.');
        hasError = true;
    }
    else if(password != repassword){
    	$('#nsiginMessage').html('Confirm password does not match.');
        hasError = true;
    }
    if(hasError == true) 
    	return false;
    
	$.getJSON(getRelativeUrl('registercustomer.html'), { username: username, password: password, 'noCache': noCache }, function(data){
		 if(data.result=="ok"){
			 location.href = getRelativeUrl('index.html'); 
		 }
		 else {
			 $('#nsiginMessage').html(data.result);		 
		 }			
	});
}

function toggleAdvancedSearch() {
	$('#AdvancedSearch').toggle();
	$('#title').focus();
}

function activateTab() {
	//Stop the other One.	
	$("ul.tabs li").removeClass("active"); //Remove any "active" class
	$(this).addClass("active"); //Add "active" class to selected tab
	$(".tab_content").hide(); //Hide all tab content
	var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
	$(activeTab).fadeIn(1000); //Fade in the active content
	
	//Start rotating the corresponding carousel.
	if($('#readerschoicecarousel').is(':visible'))
		$("#readerschoicecarousel").data('cloudcarousel').rotate(-1);
	else {
		if($("#newarrivalcarousel").data('cloudcarousel')) {
			$("#newarrivalcarousel").data('cloudcarousel').rotate(-1);
		} else {
			//This is not yet created.
			$("#newarrivalcarousel").CloudCarousel({
				reflHeight: 56,
				reflGap:2,
				xPos: 150,
				yPos: 10,
				bringToFront: true,
				beforeRotate: function(){ return !($('#shopcartid').data('overlay').isOpened()); },
				onRotate: carouselRotate
			});
		}
	}
	
	return false;
}

function clickhereproduct(relVal){
	var url = getRelativeUrl('product/') + $('body').data(relVal);
	location.href = url;
}

function crousalImageClick(id, textElement, image){
	$('body').data(id, $(image).attr("id"));
	$(textElement).fadeOut(250, function(){
		$(textElement).html($(image).attr("alt"));
		$(textElement).fadeIn(250);
	});
}

function carouselRotate(image) {
	if(this.container.id == 'readerschoicecarousel')
		crousalImageClick ('rchcrId', '#rchcrText', image);
	else if(this.container.id == 'newarrivalcarousel')
		crousalImageClick ('narcrId', '#narcrText', image);
}

function rotationTimeout() {
	var count = $('#readerschoicecarousel').data('rotationcount');
	if(!count)
		count = 0;
	
	if($('#readerschoicecarousel').data('cloudcarousel').isLoaded){
		count ++;
		
		$('#readerschoicecarousel').data('rotationcount', count);
		$('#readerschoicecarousel').data('cloudcarousel').rotate(-1);		
	}	
	
	if(count<3)
		setTimeout(rotationTimeout, 3000);
}

function shoppingCart(){
	_gaq.push(['_trackPageview', '/shoppingCart']);
	// grab wrapper element inside content
	var wrap = this.getOverlay().find(".contentWrap");
	
	var productId = $('#shopcartid').data('productId');
	$('#shopcartid').data('productId', 0); //reset it.

	if(productId && productId != 0) {
		var noCache = Date();
		wrap.load(
			getRelativeUrl('addtocart.html'),
			{productId: productId, 'noCache': noCache},
			function(data, status, XMLHttpRequest){
				if(status == 'success'){
					isInCart = true;
					var itemCount = parseInt($('#shitemcount').html());
					if(isNaN(itemCount))
						$('#shopcartid').html('Shopping Cart (<span id="shitemcount">1</span> items)');						
					else 
						$('#shitemcount').html($('#cartItemsCount').val());						
				} else {
					//There is an error loading the page. Alert user.					
				}
			}
		);
	} else {
		wrap.load(getRelativeUrl('cart.html'));
	}
}

function closeCart() {
	_gaq.push(['_trackPageview', '/closeCart']);
	$('#shopcartid').data('overlay').close();
}

function addToCart(event){
	var productId = $(this).attr('id');	
	if(isInCart == true) {
	    jConfirm('This product is already in your cart do you want add one more time?', null, function(r) {
	        if (r)
	        	addProduct(productId);
	    });
	} else {
		addProduct(productId);
	}
}

function addProduct(productId) {
	$('#shopcartid').data('productId', productId);
	$('#shopcartid').click();
}

function placeOrder() {
	_gaq.push(['_trackPageview', '/placeOrder']);
	var cart = $('#shopcartid').data('overlay');
	var wrap = cart.getOverlay().find(".contentWrap");
	wrap.load(getRelativeUrl('placeorder.html'));
}

function cartSignIn() {			
	var noCache = Date();
	var username = $('#cartUserName').val();
	var password = $('#cartPassword').val();
	
	$('#cartSiginMessage').html(' ');
	var hasError = false;
	if(username == '') {
    	$('#cartSiginMessage').html('Please enter email address.');
        hasError = true;
    }
	else if(password == '') {
    	$('#cartSiginMessage').html('Please enter password.');
        hasError = true;
    }
	if(hasError == true) 
    	return false;

    $.getJSON(getRelativeUrl('login.html'), { username: username, password: password, 'noCache': noCache }, function(data){
		 if(data.result=="ok"){
				var cart = $('#shopcartid').data('overlay');
				var wrap = cart.getOverlay().find(".contentWrap");
				noCache = Date();
				wrap.load(getRelativeUrl('finishsignin.html', { 'noCache': noCache }));
		 }
		 else {
			 $('#cartSiginMessage').html(data.result);
		 }			
	});    
}

function cartRegister() {
	var noCache = Date();
	var username = $('#cartnUserName').val();
	var password = $('#cartnPassword').val();
	var repassword = $('#cartnRePassword').val();
	
	$('#cartnSiginMessage').html(' ');
    var hasError = false;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    
    if(username == '') {
    	$('#cartnSiginMessage').html('Please enter email address.');
        hasError = true;
    }
    else if(!emailReg.test(username)) {
    	$('#cartnSiginMessage').html('Enter a valid email address.');
        hasError = true;
    }
    else if(password == '') {
    	$('#cartnSiginMessage').html('Please enter password.');
        hasError = true;
    }
    else if(password != repassword){
    	$('#cartnSiginMessage').html('Confirm password does not match.');
        hasError = true;
    }
    if(hasError == true) 
    	return false;
    
	$.getJSON(getRelativeUrl('registercustomer.html'), { username: username, password: password, 'noCache': noCache }, function(data){
		 if(data.result=="ok"){
				var cart = $('#shopcartid').data('overlay');
				var wrap = cart.getOverlay().find(".contentWrap");
				noCache = Date();
				wrap.load(getRelativeUrl('finishsignin.html'), { 'noCache': noCache });
		 }
		 else {
			 $('#cartnSiginMessage').html(data.result);
		 }			
	});
}

function finishOrder() {
	if(!$('#accept').attr('checked')){
		jAlert ("Please accept the terms and conditions.");
		return;
	}
	var noCache = Date();
	var errors = "";
	var phoneReg = /^[0-9]{10}$/;
	var altPhoneReg = /^[0](\d)$/;
	var pinReg = /^[0-9]{6}$/;
	var name = $('#cartName').val();
	if(name == '')
		errors += "<li>Please enter the Receivers Name.</li>";
	var phoneNo = $('#cartPhoneNo').val();
	if(phoneNo == '')
		errors += "<li>Please enter contact Phone Number.</li>";
	if(phoneNo != '' && !phoneReg.test(phoneNo))
		errors += "<li>Please enter valid Primary Phone Number.</li>";
	var phoneNo2 = $('#cartPhoneNo2').val();
	if(phoneNo2 != '' && phoneNo2 == phoneNo)
		errors += "<li>Alternate Number can not be same as Primary number.</li>";
	if(phoneNo2 != '' && !(phoneReg.test(phoneNo2) || altPhoneReg.test(phoneNo2)))
		errors += "<li>Please enter valid Alternate Phone Number.</li>";
	var address1 = $('#cartAddress1').val();
	if(address1 == '')
		errors += '<li>Please enter Address1.</li>';
	var address2 = $('#cartAddress2').val();
	var region = $('#cartRegion').val();
	var city = $('#cartCity').val();
	if(city == undefined || city ==  '')
		errors += '<li>Please enter the City.</li>';
	var state = $('#cartState').val();
	if(state == undefined || state == '')
		errors += '<li>Please enter the State.</li>';
	var pinCode = $('#cartPinCode').val();
	if(pinCode == undefined || pinCode == '')
		errors += '<li>Please enter the PinCode.</li>';
	if(pinCode != undefined && pinCode != '' && !pinReg.test(pinCode))
		errors += '<li>Please enter valid PinCode.</li>';

	if(errors.length != 0){
		errors = '<ul>' + errors + '</ul>';
		$('#cartSiginMessage').html(errors);
		return false;
	} else {
		$('#cartSiginMessage').html('');
	}
	
	//$('#payorder').attr('disabled', 'disabled');
	$('#payorder').hide();
	isInCart = false; //The product is paid for.

	_gaq.push(['_trackPageview', '/finishOrder']);
	var cart = $('#shopcartid').data('overlay');
	var wrap = cart.getOverlay().find(".contentWrap");
	wrap.load(getRelativeUrl('finishorder.html'), 
		{ name: name, address1: address1, address2:address2, region:region, city: city, 
			state: state, pincode:pinCode, phoneNo:phoneNo, 'noCache': noCache }); 
}

function openOrderSubmit(option)
{
	var prodcutChoosenLength = $("input[@id=productschoosen]:checked").length; 
	if ( prodcutChoosenLength == 0 )
	{
		jAlert("Please choose products ");
		return;
	}
    
	if (option == 'save')
	{
		var trackingNumber = $('#trackingNumber').val();
		if ( trackingNumber == '' )
		{
			jAlert("Please enter Tracking Number ");
			return;
		}
		document.openordersSave.action="openordersSave.html";
		document.openordersSave.submit();
	}

	if (option == 'invoice')
	{
		
		var openOrderNo = $('#openOrderNo').val();
		$('#id').val(openOrderNo);
		document.openordersSave.action="viewInvoice.html";
		document.openordersSave.submit();
	}
}



function makePayment()
{
	var paymentOption = $('input:radio[name=paymentOption]:checked').val();
	if(!paymentOption) 
	{
		jAlert("Please choose a payment option.");
		return;
	}
	$('#MakePayment').hide();
	$('#PaymentProcessing').show();
	var noCache = Date();
	_gaq.push(['_trackPageview', '/makePayment']);
	$.getJSON(getRelativeUrl('redirectPaymentGateway.html'), 
			{paymentOption: paymentOption, 'noCache': noCache }, function(data){
		location.href = data.result;		
	});
}

function deleteFromCart(id){
	var cart = $('#shopcartid').data('overlay');
	var wrap = cart.getOverlay().find(".contentWrap");
	
	var noCache = Date();
	_gaq.push(['_trackPageview', '/deletFromCart']);
	wrap.load(
		getRelativeUrl('removefromcart.html'),
		{productId: id, 'noCache': noCache},
		function(data, status, XMLHttpRequest){
			if(status == 'success'){
				var itemCount = parseInt($('#cartItemsCount').val());
				if(itemCount == 0) {
					isInCart = false;
					$('#shopcartid').html('Shopping Cart');
				} else 
					$('#shitemcount').html($('#cartItemsCount').val());						
			} else {
				//There is an error loading the page. Alert user.					
			}
		}
	);
}

function showQuntBox(event) {	
	var cur = $(this).parent();
	var sib = cur.prev();
	cur.hide();
	sib.show();
}

function changeQuantityInCart(id){
	var quantity = $('#cartqt'+id).val();
	var cart = $('#shopcartid').data('overlay');
	var wrap = cart.getOverlay().find(".contentWrap");
	
	var noCache = Date();
	_gaq.push(['_trackPageview', '/changeQuantityInCart']);
	wrap.load(
		getRelativeUrl('changeQuantity.html'),
		{productId: id, quantity:quantity, 'noCache': noCache},
		function(data, status, XMLHttpRequest){
			if(status == 'success'){
				var itemCount = parseInt($('#cartItemsCount').val());
				if(itemCount == 0) {
					isInCart = false;
					$('#shopcartid').html('Shopping Cart');
				} else 
					$('#shitemcount').html($('#cartItemsCount').val());						
			} else {
				//There is an error loading the page. Alert user.					
			}
		}
	);
}

function cartnewuser(){
	$('#cartexistinguser').hide();
	$('#cartnewuser').show();
	$('#cartnUserName').focus();
}

function cartexistinguser() {
	$('#cartnewuser').hide();
	$('#cartexistinguser').show();
	$('#cartUserName').focus();	
}

function statechange(stateVar, cityVar, regionVar, pincodeVar) {
	var state = $('#' + stateVar).val();	
    $.getJSON(getRelativeUrl('/getCityList.html'), { state: state }, function (data) {
        var city = [];
        $.each(data, function (index, obj) {
            city.push('<option value="' + obj + '">' + obj + '</option>');
        });

        var hasValue = false;
        if (city.length != 0) {
            $('#'+cityVar).html(city.join(''));
            hasValue = true;
        } else {
        	$('#'+cityVar).html('');
        }
        
        $('#'+regionVar).html('');
        $('#'+pincodeVar).html('');
        
        if(hasValue){
        	cityChange(stateVar, cityVar, regionVar, pincodeVar);
        }
        
        $('#'+cityVar).focus();        
    });
}

function cityChange(stateVar, cityVar, regionVar, pincodeVar) {
	var city = $('#' + cityVar).val();
	var state = $('#' + stateVar).val();	
    $.getJSON(getRelativeUrl('getRegionList.html'), { state: state, city: city }, function (data) {
        var region = [];
        $.each(data, function (index, obj) {
        	region.push('<option value="' + obj + '">' + obj + '</option>');
        });
        
        var hasValue = false;
        if (region.length != 0) {
            $('#'+regionVar).html(region.join(''));
            hasValue = true;
        } else {
        	$('#'+regionVar).html('');
        }

        if(hasValue){
        	regionChange(stateVar, cityVar, regionVar, pincodeVar);
        }
        $('#'+pincodeVar).html('');
        $('#'+regionVar).focus();
    });
}

function regionChange(stateVar, cityVar, regionVar, pincodeVar) {
	var region = $('#' + regionVar).val();
	var city = $('#' + cityVar).val();
	var state = $('#' + stateVar).val();	
    $.getJSON(getRelativeUrl('getPinCodeList.html'), { state: state, city: city, region: region }, function (data) {
        var pincode = [];
        $.each(data, function (index, obj) {
        	pincode.push('<option value="' + obj + '">' + obj + '</option>');
        });

        if (pincode.length != 0) {
            $('#'+pincodeVar).html(pincode.join(''));
        } else {
        	$('#'+pincodeVar).html('');
        }
    	$('#'+pincodeVar).focus();
    });
}

function showMoreDetails() {
	var str = '<p><ul><li>5 - 6 days for instock shipping.</li>';
	str += '<li>1 - 2 weeks for domestic procurement</li>';
	str += '<li>3 - 4 weeks for International procurement</li></ul></p>';
	jAlert (str);
	return false;
}
