/**
 * 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) 2009-2010 aheadWorks Co. (http://www.aheadworks.com)
 * @license    http://ecommerce.aheadworks.com/LICENSE-M1.txt
 */

var ie = 0/*@cc_on+@_jscript_version*10@*/;
$_.ie6 = $_.IE6 = ie == 56;
window.ACPTop = 200;

/* keep minicart open for*/
var keepOpen = 2500;

/* Prototype Pico wrapper */
function $_(a){return $$(a)[0]}


if (window.location.toString().search('/product_compare/') != -1){
	win = window.opener;
} else{
	win = window;
}


if (document.observe) {
    document.observe("dom:loaded", function(){
	var el1 = $$('.content-wrapper')[0];
	if (el1){
            el1.observe("mouseover", _showMiniCart);
	    el1.observe("mouseout", tryHideMiniCart);
        }

	var el2 = $$('li.cart')[0];
        if (el2){
  	//el2.observe("mouseover", _showMiniCart);
	  el2.observe("mouseout", tryHideMiniCart);
	  el2.observe("click", function(e){
               if (e.element().className=='cart-img'){_showMiniCart()};
               if (e.element().tagName != 'A'){e.stop();}
          });
        }

	document.observe('click', _hideMiniCart);

	if(typeof aw_cartDivClass == 'undefined'){
		 aw_cartDivClass =
			AW_ACP.theme == 'blank' ?
				'.block block-cart' :
				'.box base-mini mini-cart';

		if(!$_(aw_cartDivClass).tagName){
			 aw_cartDivClass =  '.block block-cart'
		}
	}
	if(typeof aw_topLinkCartClass == 'undefined'){
		 aw_topLinkCartClass = '.top-link-cart';
	}
	if(typeof aw_addToCartButtonClass == 'undefined'){
		 aw_addToCartButtonClass = '.form-button';
	}
	if(typeof aw_bigCartClass == 'undefined'){
		 aw_bigCartClass =
			AW_ACP.theme == 'modern' ?
				'.layout-1column':
				'.col-main';
	}

	if(!$_.ie6){
		/* Hangs event listener for @ADD TO CART@ links*/
		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;
			}
		}

		updateAddLinks();

	/* This hangs event listener on @DELETE@ items from cart*/
		if (typeof aw_cartDivClass != 'undefined'){
		    if(!$_(aw_cartDivClass).empty() || ((typeof AW_ACP !== 'undefined') && AW_ACP.isCartPage)){
			updateDeleteLinks();
		    }
                }
	}
    });
}
 
function setLocation(url){
	if(window.location.href.match('https://') && !url.match('https://')){
	    url = url.replace('http://','https://')
	}
	 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;
	}
}

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){
	url = getCommonUrl(url);
	showProgressAnimation();
	if (type == 'form'){
		$_('#product_addtocart_form').action += url;
		$('product_addtocart_form').request({
				onSuccess: function(transport){
					resp = transport.responseText;
					try{
						eval('resp = ' + resp);
					}catch(e){
						return obj.form.submit();
					}
				if (resp){
					hideProgressAnimation();
					if (resp.r != 'success'){
						obj.form.submit();
					} else {
						if(AW_ACP.useConfirmation && !AW_ACP.isCartPage){	
							showConfirmDialog();	
						}
						__onACPRender();
						updateCartView(resp);
					}
				} else {
					win.location.href=url;
					hideProgressAnimation();
					return;
				}
			}
		});
	}
	if (type == 'url'){
		new Ajax.Request(url, {
			onSuccess: function(transport) {
				resp = transport.responseText;
				try{
					if (typeof(resp) == 'string') eval('resp = ' + resp);
				}catch(e){
					win.location.href=url;
					hideProgressAnimation();
					return;
				}
				if (resp){
					hideProgressAnimation();
					if (resp.r != 'success'){
						win.location.href=url;
					} else {
						if(AW_ACP.useConfirmation && !AW_ACP.isCartPage){
							showConfirmDialog();
						}
						__onACPRender();
						updateCartView(resp);
					}
				} else {
					win.location.href=url;
					hideProgressAnimation();
					return;
				}
			}
		});
	}
}

function __onACPRender(){
    if(AW_ACP.onRender && AW_ACP.onRender.length){
     $A(AW_ACP.onRender).each(function(h){h(AW_ACP)})
    }
}


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)";
		}
	}
}

function updateDeleteLinks(){
	var tmpLinks = document.links;
	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{
                                var eee = Element.hasClassName(tmpLinks[i], 'btn-remove2');
				tmpLinks[i].href = 'javascript:ajaxcartprodelete("' + aw_base_url + 'ajaxcartpro/cart/remove/id/' + id +'/is_checkout/1",' + !eee + ')';
			}
		}
	}
}

function updateTopLinks(resp){ /* stub - not used in the currrent theme */ }


/* miniCart event wrappers */
function _showMiniCart(e){showMiniCart();}
function _hideMiniCart(e){
    var el = e.element().tagName.toLowerCase();
    
    if (el != 'a' && el != 'button' && el != 'textarea' && el != 'input'){
        hideMiniCart();
    }
}

var cartTimer = '';

function tryHideMiniCart(){
  if (cartTimer) clearTimeout(cartTimer);
  cartTimer = setTimeout("hideMiniCart()", keepOpen);
}

function showMiniCart(afterFinish){
    if (cartTimer) clearTimeout(cartTimer);
    if (!afterFinish) afterFinish = function(){};
    if (!isMiniCartShown()){
      $_('.content-wrapper').hide();
      $_('.cart').addClassName('cart-active')
      new Effect.SlideDown($_('.content-wrapper'), { duration:1, afterFinish : afterFinish, queue: { position: 'end', scope: 'cartBox' }});
   }
}

function hideMiniCart(beforeSetup){
    if (!beforeSetup) beforeSetup = function(){};
    if (isMiniCartShown()){
      new Effect.SlideUp($_('.content-wrapper'), {duration:1, delay:0,
       beforeSetup : beforeSetup,
       afterFinish : function(){
         $_('.cart').removeClassName('cart-active');
         $_('.content-wrapper').style.display='';
       },
       queue: { position: 'end', scope: 'cartBox' }
      });
    }
}

function isMiniCartShown(){
    return $_('.cart').hasClassName('cart-active');
}

/* minicart content update*/
function replaceItem(oldI, newI){oldI.replace(newI)}

function removeItem(i){i.slideUp({duration:1, queue: { position: 'front', scope: 'cartBox' }});}

function addItem(i, isDel){
i.style.display = 'none';
i.style.height = '60px';
   if (isDel){
     var el = $('cart-sidebar').appendChild(i);
   } else {
      el = $('cart-sidebar').insertBefore(i, $('cart-sidebar').firstDescendant());
   }
   el.slideDown({duration:1,
    queue: { position: 'front', scope: 'cartBox' },
    afterFinish : function(){
    //i.removeClassName('added')
  }
  })}


function inList(list, item){
  for (var i=0;i<list.length;i++){
     if (list[i].select('.product-name')[0].firstChild.innerHTML == item.select('.product-name')[0].firstChild.innerHTML){ return i;}
  }
  return false;
}

function mutateMiniCart(isDel){
if (typeof(isDel) == 'undefined') isDel = false;
/*$_('#cart-sidebar').slideUp({duration:1, delay:1, queue: 'end',
  afterFinish : function(){
		var newContent = $('tmpdiv').select('div.content-inner')[0];
		$_('.block-cart').select('div.content-inner')[0].innerHTML = newContent.innerHTML;
  }
});
*/
var newContent = $('tmpdiv').select('.content-inner')[0].innerHTML;

     var oldCartList = $('cart-sidebar').select('li');
     var newCartList = $('tmpdiv').select('li');

if (!isDel){
 if ($('messages_product_view') && !$('messages_product_view').innerHTML.trim().empty()){
     new Effect.SlideUp($('messages_product_view'), {duration:1, delay:0,
       afterFinish : function(){$('messages_product_view').remove()},
       queue: { position: 'end', scope: 'messageBox' }
      });
 }
}

if (!isMiniCartShown()) showMiniCart();

    $('cart-sidebar').select('li').each(function(e,i){
         if (inList(newCartList, e) === false ) removeItem(e)}
     )

     $('tmpdiv').select('li').each(function(e,i){
         _r = inList(oldCartList, e);
         if ( _r !== false) replaceItem(oldCartList[_r], e)
          else{
             addItem(e, isDel);
          }

      })

  
$('tmpdiv').slideUp({duration:0, delay:0, queue: { position: 'end', scope: 'cartBox' },
  afterFinish : function(){
    $_('.block-cart').select('div.content-inner')[0].innerHTML = newContent;
    updateDeleteLinks();
  }
});
    
}


function updateCartView(resp, isDel ){
$('tmpdiv').innerHTML = resp.minicart;
mutateMiniCart(isDel);
    if (AW_ACP.isCartPage) updateBigCartView(resp);
    updateTopLinks(resp);

//    $('tmpdiv').innerHTML = resp.minicart;
//    mutateMiniCart(isDel);
    updateDeleteLinks();
}

function updateCartSilent(resp){
    $('tmpdiv').innerHTML = resp.minicart;
    $_('.block-cart').select('div.content-inner')[0].innerHTML = $('tmpdiv').select('.content-inner')[0].innerHTML;
    updateBigCartView(resp);
    updateDeleteLinks();
}

window.updateBigCartView = function (resp){
	
	$_(aw_bigCartClass).innerHTML = resp.cart
	if($_('#shopping-cart-table')){
		decorateTable('shopping-cart-table')
	}
	
	updateDeleteLinks();
	updateTopLinks(resp);
	updateAddLinks();
	
	var scripts = resp.cart.match(/<script[^>]*>([^<]+)<\/script>/gim);
	for(var i=0; i<scripts.length; i++){
		var code = scripts[i].match(/<script[^>]*>([^<]+)<\/script>/im)[1].replace(/var\s+/g, '');
		try{ 
			eval(code)
		}catch(e){
		}
	}
	
}


function ajaxcartprodelete(url, isMiniCart){
	showProgressAnimation();
	url = getCommonUrl(url)
	new Ajax.Request(url, {
			onSuccess: function(transport) {
				resp = transport.responseText;
				if (typeof(resp) == 'string') eval('resp = ' + resp);
				hideProgressAnimation();
				__onACPRender()
				if (isMiniCart || isMiniCartShown()){
                                    updateCartView(resp, true);
                                } else {
                                    updateCartSilent(resp);
                                };
			}
	});
}

function showProgressAnimation(){
	var pW = 328;
	var pH = 186;
	p = win.$_('.ajaxcartpro_progress');
	
	p.style.width = pW + 'px';		
	p.style.height = pH + 'px';

        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 = 328;
	var pH = 186;
	p = $_('.ajaxcartpro_confirm');
	p.style.width = pW + 'px';		
	p.style.height = pH + 'px';
	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';	
	}

	if ($('aw_acp_continue')){
             $('aw_acp_continue').onclick = function(e){
		e = e||event;
		if(e.preventDefault)
			e.preventDefault()

		$_('.ajaxcartpro_confirm').style.display='none';
		hideMiniCart();
		return false;
             }
	}

	if ($('aw_acp_checkout')){
                $('aw_acp_checkout').onclick = function(e){
		   $_('.ajaxcartpro_confirm').style.display='none'; return true;
                }
	}
}

function hideProgressAnimation(){
	$_('.ajaxcartpro_progress').style.display = 'none';
}

function getCommonUrl(url){
	if(window.location.href.match('www.') && url.match('http://') && !url.match('www.')){
		url = url.replace('http://', 'http://www.');
	}else if(!window.location.href.match('www.') && url.match('http://') && url.match('www.')){
		url = url.replace('www.', '');
	}
	return url;
}