var cartPopup;
var STFModal;
var ajaxLock = false;
$(document).ready(function() {
	if(document.getElementById('fp_frame')) {
		createFPSlider();
	}
	if(document.getElementById('cartFile') && !document.getElementById('cartFile_disable')) {
		cartPopup = new cartFile();
	} else {
	    cartPopup = new emptyCartFile();
	    $('#cartFile .tab').addClass('off');
	}
	if(document.getElementById('modal')) {
		STFModal = new SendToFriend();
	}
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		$('div.title_side').after('<div class="title_side_bottom"></div>');
	}
	if(document.getElementById('excerptBox')) {
		setExcerpt();
	}
	/*if(document.getElementById('secMenu')) {
	    createSecMenu();
	}*/
	/*if(document.getElementById('hdnCompleteContent')) {
	    sendOrderConfirmation(document.getElementById('hdnCompleteContent').value);
	}*/
});

function openPlayer(id){
	var audioplayer = window.open ("/audioPlayer.aspx?id="+id, "audioplayer", "resizable=0,location=0,status=0,scrollbars=0,width=444,height=153");
	audioplayer.focus();
}

function IsUSorCanada(value){
	if(value==840 || value==124){
	    return true;
	}
	return false;
}

function UpdateRequiredClass(input){
	if(!IsUSorCanada($('.EktronCheckout_CountrySelect').val()))
	{
	    $(input).parent().removeClass('EktronCheckout_Required'); 
	} else {
	    $(input).parent().addClass('EktronCheckout_Required');
	}
}

function AddOther(input){
	if(!IsUSorCanada($('.EktronCheckout_CountrySelect').val()))
	{
	    $(input).append($("<option></option>").attr("value",'0').text('Other')); 
	}
}

function createFPSlider() {

	var slider = new filmstrip();
	slider.frame = document.getElementById('fp_frame');
	slider.next = document.getElementById('fp_next');
	slider.previous = document.getElementById('fp_previous');
	slider.events.onAfterInit = function() {
		var ul = slider.frame.getElementsByTagName('ul')[0];
		
		var lis = slider.frame.getElementsByTagName('li');
		var key = document.createElement('ul');
		for(var x=0;x<lis.length;x++) {
			var a = document.createElement('a');
			var li = document.createElement('li');
			a.rel = x+1;
			a.id = slider.settings.prefix + "key" + (x+1);
			a.onclick = function() {
				slider.go(this.rel);
			}
			if(x == 0) {
				a.className = "active";
			}
			li.appendChild(a);
			key.appendChild(li);
		}
		document.getElementById('fp_key').appendChild(key);
	};
	slider.events.onBeforeMove = function(num) {
		document.getElementById(slider.settings.prefix + "key" + slider.current).className = "";
		document.getElementById(slider.settings.prefix + "key" + num).className = "active";
	}
	slider.settings.scrollWheel = true;
	slider.settings.ease = "quartInOut";
	slider.anim.duration = 70;
	slider.settings.setRotate = 7000;
	slider.settings.pauseOnHover = true;
	slider.init();

}

function emptyCartFile() {
    this.UpdateCart = function(html) { };
	this.close = function() { };
}

function cartFile() {
	var self = this;
	this.frame = document.getElementById('cartFile');
	this.toggle = document.getElementById('cartFile_toggle');
	this.start = 966;
	this.ceil = this.start - document.getElementById('cartFile_wrap').offsetHeight + 8;
	this.anim = { top:this.start, timer:null, status:"closed", time:0, begin:0.0, change:0.0 };
	this.settings = { easeDown:"sineOut", easeUp:"sineOut", easeAdjust:"bounceOut", speed:15, durationDown:50, durationUp:70, durationAdjust:50 };
	$('#cartFile_tab').click(function(e) {
        e.preventDefault();
        if(self.anim.status == "closed") {
                self.open();
        }
        else if(self.anim.status == "open") {
                self.close();
        }
	});
	/*$(this.frame).find('a.remove').click(function(e) {
		e.preventDefault();
		// Do Ajax to remove the product item from the cart
		$(this).parents('li').remove();
		$(self.frame).find('li:first').addClass('first');
		self.ceil = self.start - document.getElementById('cartFile_wrap').offsetHeight + 8;
		this.updateItemNumber();
		self.readjust();
	});*/
	this.UpdateHeight = function(html) {
		self.ceil = self.start - document.getElementById('cartFile_wrap').offsetHeight + 8;
	};
	this.UpdateCartWithOpen = function(html) {
	    $('#cartFile_wrap').html(html);
	    this.updateItemNumber();
        this.readjust();
        if(this.anim.status == "closed") {
            this.open();
        }
	};
	this.UpdateCart = function(html) {
	    $('#cartFile_wrap').html(html);
	    this.updateItemNumber();
        this.readjust();
	};
	this.updateItemNumber = function() {
	    var itemCount = self.frame.getElementsByTagName('li').length - 1;
	    document.getElementById('cartFile_items').innerHTML = itemCount + ((itemCount==1) ? " item":" items");
	    //document.getElementById('cartFile_items').innerHTML = (self.frame.getElementsByTagName('li').length - 1) + " items";
	};
	this.open = function() {
		clearInterval(this.anim.timer);
		this.anim.timer = null;
		this.anim.status = "open";
		this.toggle.innerHTML = "Close Cart";
		this.frame.style.zIndex = "150";
		this.anim.time = 0;
		this.anim.begin = this.anim.top;
		this.anim.change = this.ceil - this.anim.begin;
		this.anim.timer = setInterval(function() { self.grow() },self.settings.speed);
	};
	this.grow = function() {
		if(this.anim.time > this.settings.durationDown) {
			clearInterval(this.anim.timer);
			this.anim.timer = null;
		}
		else {
			this.anim.top = c2.ease[this.settings.easeDown](this.anim.time, this.anim.begin, this.anim.change, this.settings.durationDown);
			this.frame.style.top = -this.anim.top + "px";
			this.anim.time++;
		}
	};
	this.close = function() {
		clearInterval(this.anim.timer);
		this.anim.timer = null;
		this.anim.status = "closed";
		this.toggle.innerHTML = "Open Cart";
		this.anim.time = 0;
		this.anim.begin = this.anim.top;
		this.anim.change = this.start - this.anim.begin;
		this.anim.timer = setInterval(function() { self.shrink() },self.settings.speed);
	};
	this.shrink = function() {
		if(this.anim.time > this.settings.durationUp) {
			clearInterval(this.anim.timer);
			this.anim.timer = null;
			this.frame.style.zIndex = "50";
		}
		else {
			this.anim.top = c2.ease[this.settings.easeUp](this.anim.time, this.anim.begin, this.anim.change, this.settings.durationUp);
			this.frame.style.top = -this.anim.top + "px";
			this.anim.time++;
		}
	};
	this.readjust = function() {
	    this.UpdateHeight();
		clearInterval(this.anim.timer);
		this.anim.timer = null;
		this.anim.time = 0;
		this.anim.begin = this.anim.top;
		this.anim.change = this.ceil - this.anim.begin;
		this.anim.timer = setInterval(function() { self.adjust() },self.settings.speed);
	};
	this.adjust = function() {
		if(this.anim.time > this.settings.durationAdjust) {
			clearInterval(this.anim.timer);
			this.anim.timer = null;
		}
		else {
			this.anim.top = c2.ease[this.settings.easeAdjust](this.anim.time, this.anim.begin, this.anim.change, this.settings.durationAdjust);
			this.frame.style.top = -this.anim.top + "px";
			this.anim.time++;
		}
	};
}

function createSecMenu() {
    $('#secMenu li.closed>a').click(function(e) {
        e.preventDefault();
        if(this.parentNode.className == "closed") {
            this.parentNode.className = "opened";
        }
        else {
            this.parentNode.className = "closed";
        }
    });
}

function setExcerpt () {
	$('#excerptBox').jScrollPane({showArrows:true, scrollbarWidth: 20});
	var readEx = document.getElementById('readEx');
	var closeEx = document.getElementById('closeExcerpt');
	var prodDetail = $('.productDetail')[0];
	var excerptCon = document.getElementById('excerptContain');
	excerptCon.style.display = 'none';
	readEx.onclick = function() {
		prodDetail.style.display = 'none';
		excerptCon.style.display = 'block';
		return false;
	}
	closeEx.onclick = function() {
		prodDetail.style.display = 'block';
		excerptCon.style.display = 'none';
		return false;
	}
}


function Login_EnterPressed(e, controlId)
{
    if(is_enterKey(e))
    {
        if(Ektron_Ecommerce_CheckoutClass.GetObject(controlId).LoginBT()){
            window.location.href='#';
        }
        return false;
        /*return enterKey(e, btnId);
        var btn = document.getElementById(btnId);
        if(btn)
            btn.click();
        return false;*/
    }
    
    return true;
}

function Cart_AddProduct(a,pid,quantity) {
    if(ajaxLock == true){
        return;
    } else {
        ajaxLock = true;
    }
    //if(!( -1<quantity && quantity<1000 ) || !(is_integer(quantity)) ){
     //   quantity = 1;
    //}
    if (!quantity){
        ajaxLock = false;
        return;
    }
    if (quantity != -1){
        if (!is_integer(quantity))
            quantity = 1;
        if (quantity >= 1000)
            quantity = 1;
    }
    
    var moreMsg = a.nextSibling;
    if (moreMsg){
        moreMsg.innerHTML = 'Adding...';
    }
    
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/Cart_AddProduct",
        data: "{'ProductID':"+pid+",'Quantity':"+quantity+"}",
        dataType: "json",
        success: function(result, textStatus) {
            cartPopup.UpdateCartWithOpen(result);
            if (moreMsg){
                moreMsg.innerHTML = 'Added to cart!';
            }
        },
        error: function(request, status, err) {
            //alert("Error: "+pid+status+err);
            if (moreMsg){
                moreMsg.innerHTML = '';
            }
        },
        complete: function (XMLHttpRequest, textStatus) {
           ajaxLock = false;
        }
    });
    
}

function is_integer(num) {
    return (/^\d+$/.test(num));
}
function is_inputvalid(text) {
    return !(/&#+/.test(text));
}
function is_numberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;

    return true;
}
function is_enterKey(evt){
    if(!evt){
        evt = window.event;
    }
    var charCode = (evt.which) ? evt.which : evt.keyCode
     if (charCode != '13'){
        return false;
        }
    return true;
}

function Cart_RemoveProduct(pid) {
    if(ajaxLock == true){
        return;
    } else {
        ajaxLock = true;
    }
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/Cart_RemoveProduct",
        data: "{'ProductID':"+pid+"}",
        dataType: "json",
        success: function(result, textStatus) {
            cartPopup.UpdateCartWithOpen(result);
        },
        error: function(request, status, err) {
            //alert("Error: "+pid+status+err);
        },
        complete: function (XMLHttpRequest, textStatus) {
           ajaxLock = false;
        }
    });
}

function Cart_QuantityKeyPress(e){
    return (is_numberKey(e)) ? Cart_EnterPressed(e) : false;
}

function Cart_EnterPressed(e){
    return enterKey(e,'btnCartUpdate');
}

function Cart_EnterKeyPreHackUpdateSubtotalPressedEvent(e){
    if(is_enterKey(e)){
        Cart_EnterKeyPreHackUpdateSubtotalPressed(e)
    }
    if(is_numberKey(e) || is_enterKey){ return true; }
    return true;
}

function Cart_EnterKeyPreHackUpdateSubtotalPressed(e){
   Cart_UpdateStoreCart();
   window.location = window.location;
}

function StoreCart_KeyPress(e){
    if(is_enterKey(e)){
        Cart_UpdateStoreCart();
        window.location = window.location;
        return false;
    }
    return true;
}

function Cart_QuantityChanged(input, q_orig){
    if(input.value == q_orig)
        return;

    var btnCheckout = document.getElementById('btnCartCheckout');
    var btnUpdate = document.getElementById('btnCartUpdate');
    
    if(btnCheckout && btnUpdate){
        btnCheckout.style.display = 'none';
        btnUpdate.style.display = 'block';
    }
}
function Cart_QuantityUpdate(){

    //// Display proceed to checkout.
    //var btnCheckout = document.getElementById('btnCartCheckout');
    //var btnUpdate = document.getElementById('btnCartUpdate');
    
    Cart_UpdateProducts();

    //// Display proceed to checkout.
    //if(btnCheckout && btnUpdate){
    //    btnUpdate.style.display = 'none';
    //    btnCheckout.style.display = 'block';
    //}
}

function Cart_UpdateProducts()
{
    var btnCheckout = document.getElementById('btnCartCheckout');
    var btnUpdate = document.getElementById('btnCartUpdate');
    
    if(btnUpdate.style.display != 'block')
        return;
        
    
    
    var cartFile = document.getElementById('cartFile_wrap');
    var inputs = cartFile.getElementsByTagName('input');
    
    Cart_UpdateProductsCore(inputs);
    
    if(btnCheckout && btnUpdate){
        btnUpdate.style.display = 'none';
        btnCheckout.disabled = '';
        btnCheckout.style.display = 'block';
    }
}

function Cart_UpdateStoreCart()
{
    var inputs = $('table.cart tr.rowSku :input');
    Cart_UpdateProductsCore(inputs);
    cartPopup.close();
}

function Cart_UpdateProductsCore(inputs)
{
    
    if(ajaxLock == true){
        return;
    } else {
        ajaxLock = true;
    }
    /*if(!( 0<quantity && quantity<1000 ) ){
        quantity = 1;
    }*/
    var productIds = '';
    var quantitys = '';
    
    var count = inputs.length/3;
    for(var i = 0; i < count; i++){
        var productId = inputs[3*i+1].value;
        var quantity = inputs[3*i+2].value;
        productIds = productIds + productId + ' ';
        quantitys = quantitys + quantity + ' ';
    }
    
    var data = "{'productIds':'"+productIds+"','quantitys':'"+quantitys+"'}";

    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/Cart_UpdateProducts",
        data: data,
        dataType: "json",
        success: function(result, textStatus) {
            cartPopup.UpdateCart(result);
        },
        error: function(request, status, err) {
            ;
            //alert('Error: Unable to update cart. '+status+' '+err); // commented out so we dont get annoying popup when clicking too fast.
        },
        complete: function (XMLHttpRequest, textStatus) {
           // Display proceed to checkout.
            ajaxLock = false;
            return true;
        }
    });
}


function Checkout_DeleteAddress(selectId)
{
    var select = document.getElementById(selectId);
    if (!select || !select.selectedIndex || !select.options)
        return;
        
    var addressId = select.options[select.selectedIndex].value;
    
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/Checkout_DeleteAddress",
        data: "{'addressId':"+addressId+"}",
        dataType: "json",
        success: function(result, textStatus) {
            alert('address removed!');
        },
        error: function(request, status, err) {
            alert('address remove failed');
        },
        complete: function (XMLHttpRequest, textStatus) {
            ajaxLock = false;
            return true;
        }
    });
}

function SendToFriend() {
	var self = this;
	this.validationObj = new formValidation();
	this.FromName = '';
	this.FromEmail = '';
	this.ToName = '';
	this.ToEmail = '';
	this.Message = '';
	
	this.Send = function() {
	    self.UpdateValues();
	    if(self.validationObj.submit()){
	        self.Ajax();
	    }
	};
	
	this.Open = function() {
	    $('#modal').show();
	    $('#overlay').show();
	    $('#modal').html($('#modalSource').html());
	    self.validationObj.form = document.getElementById('modal');
        self.validationObj.init();
	};
	
	this.Close = function() {
	    $('#modal').hide();
	    $('#overlay').hide();
	};
	
	this.Success = function() {
	    $('#modal').html($('#modalSource_Success').html());
	};
	
	this.UpdateValues = function() {
	    self.FromName = $('#modal .FromName').val();
	    self.FromEmail = $('#modal .FromEmail').val();
	    self.ToName = $('#modal .ToName').val();
	    self.ToEmail = $('#modal .ToEmail').val();
	    self.Message = $('#modal .Message').val();
	};
	
	this.Stringify = function() {
	    var obj = {};
	    obj.from_name = self.FromName;
	    obj.from_email = self.FromEmail;
	    obj.to_name = self.ToName;
	    obj.to_email = self.ToEmail;
	    obj.message = self.Message;
	    return JSON.stringify(obj);
	};
	
	this.Ajax = function() {
	   $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/storeServices.asmx/ShareProduct",
            data: self.Stringify(),
            dataType: "json",
            success: function(result, textStatus) {
                self.Success();
            },
            error: function(request, status, err) {
                //alert("Error: "+request+status+err);
            },
            complete: function (XMLHttpRequest, textStatus) {
                ;
            }
        }); 
	};
	
	this.OnKeyPress = function SendToFriend(e){
        if(is_enterKey(e)){
            this.Send();
            return false;
        }
        return true;
    }
}


function sendOrderConfirmation(orderId){

    if (!orderId)
        return;

    var data = "{";
    data += ("'orderId':"+orderId+"");
    data += "}";
    
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/SendOrderConfirmation",
        data: data,
        dataType: "json",
        success: function(result, textStatus) {
            //alert('success');
        },
        error: function(request, status, err) {
            //alert('failed');
        },
        complete: function (XMLHttpRequest, textStatus) {
            return true;
        }
    });
}

function storeShipDeleteBoxes(){
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/storeShipDeleteBoxes",
        data: "{}",
        dataType: "json",
        success: function(result, textStatus) {
            alert('success');
        },
        error: function(request, status, err) {
            alert('failed');
        },
        complete: function (XMLHttpRequest, textStatus) {
            return true;
        }
    });
}

function storeShipAddOrderId(orderId){
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/storeShipAddOrderId",
        data: "{'orderId':'"+orderId+"'}",
        dataType: "json",
        success: function(result, textStatus) {
            //alert('success');
        },
        error: function(request, status, err) {
            //alert('failed');
        },
        complete: function (XMLHttpRequest, textStatus) {
            return true;
        }
    });
}

function storePurchaseOrderAddOrderId(orderId){
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/storeServices.asmx/storePurchaseOrderAddOrderId",
        data: "{'orderId':'"+orderId+"'}",
        dataType: "json",
        success: function(result, textStatus) {
            //alert('success: ' + result);
        },
        error: function(request, status, err) {
            //alert('failed: ' + result);
        },
        complete: function (XMLHttpRequest, textStatus) {
            return true;
        }
    });
}

function creditCardChange(){
    var d = new Date();
    var year = d.getFullYear() + 1;
    if( $('.EktronCheckout_CreditCardTypeSelect').val() == 6 ){
        $('.EktronCheckout_CreditCardNumber').parent().find('.label').html('*Purchase Order Number');
        
        //ccid
        $('.EktronCheckout_CCID').find('input').val('123');
        $('.EktronCheckout_CCID').parent().css('visibility','hidden');
        
        //month
        $('.EktronCheckout_ExpirationMonthSelect').val('02');
        $('.EktronCheckout_ExpirationYearSelect').val(year);
        $('#expire_id').css('visibility','hidden');
    } else {
        $('.EktronCheckout_CreditCardNumber').parent().find('.label').html('*Credit Card Number');
        
        //ccid
        $('.EktronCheckout_CCID').find('input').val('');
        $('.EktronCheckout_CCID').parent().css('visibility','visible');
        
        //month
        $('#expire_id').css('visibility','visible');
        $('.EktronCheckout_ExpirationMonthSelect')[0].selectedIndex = 0;
        $('.EktronCheckout_ExpirationYearSelect')[0].selectedIndex = 0;
    }
}
//