/**
 * aheadWorks Co.
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the EULA
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://ecommerce.aheadworks.com/LICENSE-M1.txt
 *
 * @category   AW
 * @package    AW_Ajaxcartpro
 * @copyright  Copyright (c) 2003-2009 aheadWorks Co. (http://www.aheadworks.com)
 * @license    http://ecommerce.aheadworks.com/LICENSE-M1.txt
 */
 
var aw_cartDivClass = '.box base-mini mini-cart';
var aw_topLinkCartClass = '.top-link-cart';
var aw_addToCartButtonClass = '.form-button';
var aw_bigCartClass = '.col-main';

/*needed for popupcart*/
function hasClass (o,className) {
   var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
   return pattern.test(o.className); //to check for the class
}
 
function addClass (o,className) {
   if (!o.hasClass(className)) { //if the class isn't there already
      o.className += (' ' + className); //append it to the end of the class list
   }
}
 
function removeClass (o,className) {
   var pattern = new RegExp('(^|\\s)' + className + '(\\s|$)'); //use this regexp
   o.className = o.className.replace(pattern, ' '); //to make a search and replace by a blank space
}

if (window.location.toString().search('/product_compare/') != -1){
	var win = window.opener;
}
else{
	var win = window;
}

function setLocation(url){

	 if(AW_ACP.isCartPage && ((url.search('/add') != -1 ) || (url.search('/remove') != -1 )) ){
		ajaxcartsend(url+'awacp/1/is_checkout/1', 'url', '', '');
	}else if (url.search('checkout/cart/add') != -1 ){
		ajaxcartsend(url+'awacp/1', 'url', '', '');
	}else{
		window.location.href = url;
	}
}

var cnt1 = 20;
__intId = setInterval(
	/* Hangs event listener for @ADD TO CART@ links*/
	function(){
		cnt1--;
		
		if(typeof productAddToCartForm != 'undefined'){
			try {
				// This fix is applied to magento <1.3.1
				$_('#product_addtocart_form').$_(aw_addToCartButtonClass).setAttribute('type', 'button');
			}catch(err){
				
			}
			productAddToCartForm.submit = function(url){
				if(this.validator && this.validator.validate()){
                                        ajaxcartsend('?awacp=1', 'form', this, '');
				}
				return false;
			}
			clearInterval(__intId);
		}
		if(!cnt1) clearInterval(__intId);
	},
	500
);

var cnt2 = 20;
__intId2 = setInterval(
	/*This hangs event listener on @DELETE@ items from cart*/
	function(){	
		cnt2--;
		if(!$_(aw_cartDivClass).empty() || ((typeof AW_ACP !== 'undefined') && AW_ACP.isCartPage)){
			updateDeleteLinks();
			clearInterval(__intId2);
		}
		if(!cnt2) clearInterval(__intId);
	},
	500
);





function setPLocation(url, setFocus){
	if (url.search('checkout/cart/add') != -1){ //CART ADD
		window.opener.focus();
		ajaxcartsend(url+'/awacp/1', 'url', '');
	}
	else{
		if(setFocus) {
			window.opener.focus();
		}
		window.opener.location.href = url;
	}
}

function ajaxcartsend(url, type, obj){
	jQuery('div#popup').hide('fast');
	showProgressAnimation();
	if (type == 'form'){		
		$_('#product_addtocart_form').action += url;	
		$_('#product_addtocart_form').POST(			
			function(resp){
				hideProgressAnimation();
				if (resp.r != 'success'){
					obj.form.submit();
				}
				else{
					if(AW_ACP.useConfirmation){	
						//showConfirmDialog();	
					}
					updateCartView(resp);
				}
			}
		);
	}
	if (type == 'url'){
		$_(url).GET(
			function(resp){
				hideProgressAnimation();
				if (resp.r != 'success'){
					win.location.href=url;
				}
				else{		
					if(AW_ACP.useConfirmation){	
						//showConfirmDialog();	
					}
					updateCartView(resp);
				}
			}
		);
	}
}

function updateDeleteLinks(){
	var tmpLinks = document.links;//win.$_(aw_cartDivClass).getElementsByTagName('a',win.$_(aw_cartDivClass));
	//alert(tmpLinks.length);
	for (i=0; i<tmpLinks.length; i++){
		if (tmpLinks[i].href.search('checkout/cart/delete') != -1){
			url = tmpLinks[i].href.replace(/\/uenc\/.+,/g, "");
			var del = url.match(/delete\/id\/\d+\//g);
			var id = del[0].match(/\d+/g);
			if (win.location.protocol == 'https:'){
				aw_base_url = aw_base_url.replace("http:", "https:");
			}	
			if(!AW_ACP.isCartPage){
				tmpLinks[i].href = 'javascript:ajaxcartprodelete("' + aw_base_url + 'ajaxcartpro/cart/remove/id/' + id +'")';
			}else{
				tmpLinks[i].href = 'javascript:ajaxcartprodelete("' + aw_base_url + 'ajaxcartpro/cart/remove/id/' + id +'/is_checkout/1")';
			}
		}
	}
}

function updateTopLinks(resp){
	win.$_(aw_topLinkCartClass).innerHTML = resp.links;
}
function updateCartView(resp){
	if(AW_ACP.isCartPage){
		return updateBigCartView(resp);
		}

	var oldHeight = win.$_(aw_cartDivClass).offsetHeight;

	/*var tmpDiv = win.document.createElement('div');
	tmpDiv.innerHTML = resp.cart;

	var tmpParent = win.$_(aw_cartDivClass).parentNode;
	tmpParent.replaceChild(tmpDiv.firstChild, win.$_(aw_cartDivClass));*/
	
	//var cart = $('ajaxcart_bottomcart');
	//cart.innerHTML = resp.cart;
	jQuery('#ajaxcart_bottomcart').html(resp.cart);
	jQuery('#ajaxcart_bottomcart').show();
	initCart();
	if (Mage.Cookies.get('cart-state')=='closed') {
		jQuery('#bottom_cart_closed').hide("fast");
		jQuery('#ajaxcart_bottomcart').show('slow');
		//set cart state in the cookie
		Mage.Cookies.set('cart-state','opened');
	//} else new Effect.Highlight(cart,{ startcolor: '#ffff99',endcolor: '#CCCCCC' });
        }

        else if(typeof(cart) != 'undefined')
            new Effect.Highlight(cart,{ startcolor: '#ffff99',endcolor: '#CCCCCC' });

	
	setTimeout( function() {
		jQuery('#ajaxcart_bottomcart').hide('fast');
	}, 4000 ); 
	//Details popup support
	truncateOptions();
	var newHeight = win.$_(aw_cartDivClass).offsetHeight;
	
	/*if (aw_ajaxcartpro_cartanim == 'opacity'){
		$_(win.$_(aw_cartDivClass)).mutate(
			{opacity:0}, 
			{opacity:1},
			30
		);
	}*/
	if (aw_ajaxcartpro_cartanim == 'grow'){
		$_(win.$_(aw_cartDivClass)).style.overflow = 'hidden';
		$_(win.$_(aw_cartDivClass)).mutate(					
			{opacity:0, height: oldHeight + 'px'},
			{opacity:1, height: newHeight + 'px'},
			30
		);
	}
	if (aw_ajaxcartpro_cartanim == 'blink'){
		$_(win.$_(aw_cartDivClass)).mutate(
			{opacity:0}, 
			{opacity:1},
			10
		);
	}
	updateDeleteLinks();
	updateTopLinks(resp);
	//hCarousel = new UI.Carousel("horizontal_carousel");
}

function updateBigCartView(resp){
	$_(aw_bigCartClass).innerHTML = resp.cart
	if($_('#shopping-cart-table')){
		decorateTable('shopping-cart-table')
	}
	updateDeleteLinks();
	updateTopLinks(resp);
	updateAddLinks();
}


function ajaxcartprodelete(url){	
	showProgressAnimation();
	$_(url).GET(
		function(resp){			
			hideProgressAnimation();
			updateCartView(resp, '');
		}
	);
}

function showProgressAnimation(){
	var pW = 260;
	var pH = 150;
	p = win.$_('.ajaxcartpro_progress');
	p.style.width = pW + 'px';		
	p.style.height = pH + 'px';
	p.style.border = '3px solid #666666';
	if ($_.ie && !navigator.appVersion.match("8")){
		p.style.position = 'absolute';
	}
	if (aw_ajaxcartpro_proganim == 'center'){		
		p.style.top = (screen.height/2) - (pH) + 'px';
	}
	if (aw_ajaxcartpro_proganim == 'top'){		
		p.style.top = '0px';
	}
	if (aw_ajaxcartpro_proganim == 'bottom'){
		p.style.bottom = '0px';		
	}
	if (aw_ajaxcartpro_proganim != 'none'){
		p.style.display = 'block';	
	}
	
}


function showConfirmDialog(){
	var pW = 260;
	var pH = 104;
	p = $_('.ajaxcartpro_confirm');
	p.style.width = pW + 'px';		
	p.style.height = pH + 'px';
	
	if ($_.ie && !navigator.appVersion.match("8")){
		p.style.position = 'absolute';
	}else{
		p.style.position = 'fixed';
		if (aw_ajaxcartpro_proganim == 'center'){		
			p.style.top = (screen.height/2) - (pH) + 'px';
		}
		if (aw_ajaxcartpro_proganim == 'top'){		
			p.style.top = '0px';
		}
		if (aw_ajaxcartpro_proganim == 'bottom'){
			p.style.bottom = '0px';		
		}
	}
	if (aw_ajaxcartpro_proganim != 'none'){
		p.style.display = 'block';	
	}
}

function hideProgressAnimation(){
	$_('.ajaxcartpro_progress').style.display = 'none';
}

window.onload = function(){
	updateAddLinks()
	
	// Some other onclicks
	/* $_('#aw_acp_continue').onclick = function(e){
		e = e||event;
		if(e.preventDefault)
			e.preventDefault()
		$_('.ajaxcartpro_confirm').style.display='none'; return false;
	} */
	
	/* $_('#aw_acp_checkout').onclick = function(e){
		//$_('.ajaxcartpro_confirm').style.display='none'; return true;
	} */	
	
	if(!$_(aw_cartDivClass).empty() || ((typeof AW_ACP !== 'undefined') && AW_ACP.isCartPage)){
		updateDeleteLinks();
	}
	
} 

function updateAddLinks(){
	var ats = document.links;
	for (i=ats.length-1; i>=0; i--){
		if (ats[i].href.search('checkout/cart/add') != -1){
			ats[i].onclick = function(link){
				return function(){
					setLocation(link)
				}
			}(ats[i].href);
			ats[i].href="javascript:void(0)";
		}
	}
}

//lets add some jquery what the hell
jQuery(document).ready( function() {
	initCart();
});

var visibleCount = 3;
var elWidth = 0;
var visibleWidth = 0;
var curPos = 0;
var itemsCount = 0;
function calculateCartWidth()
{
	elWidth = jQuery('#cart_products_list li:first').width();
	if(elWidth)
	{
		visibleWidth = elWidth * visibleCount;
		itemsCount = jQuery("#cart_products_list li").length;
	}
}

function cartNext()
{
	if(visibleWidth && elWidth && itemsCount) {
		if(curPos + visibleWidth < elWidth * itemsCount)
		{
			curPos += visibleWidth;
			jQuery("#cart_products_list").animate({left: -curPos + "px"}, 1000);
		}
	}
}

function cartPrev()
{
	if(visibleWidth && elWidth && itemsCount) {
		if(curPos > 0)
		{
			curPos -= visibleWidth;
			jQuery("#cart_products_list").animate({left: -curPos + "px"}, 1000);
		}
	}
}
function initCarousel()
{
	calculateCartWidth();
	jQuery('div.previous_button').click(function(){
		cartPrev();
	});
	jQuery('div.next_button').click(function(){
		cartNext();
	});
}

function initCart()
{
	jQuery("a[href='#close-cart']").click(function(){
		jQuery('#ajaxcart_bottomcart').hide("fast");
		jQuery('#bottom_cart_closed').show('slow');
		Mage.Cookies.set('cart-state','closed');
		return false;
	});
	jQuery("a[href='#show-cart']").click(function(){
		jQuery('#bottom_cart_closed').hide("fast");
		jQuery('#ajaxcart_bottomcart').show('slow');
		Mage.Cookies.set('cart-state','opened');
		return false;
	});
	//set cookie
	
	if (!Mage.Cookies.get('cart-state')) {
		Mage.Cookies.set('cart-state','closed');
	}
	
	if (Mage.Cookies.get('cart-state')==null) {
		Mage.Cookies.set('cart-state','closed');
	}
	initCarousel();
}
