/**
 * 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 ie = 0/*@cc_on+@_jscript_version*10@*/;
$_.ie6 = $_.IE6 = ie == 56;
 
if(typeof aw_cartDivClass == 'undefined'){
 var aw_cartDivClass = 
 AW_ACP.theme == 'blank' ?
 '.block block-cart' :
 '.box base-mini mini-cart';
 
}
if(typeof aw_topLinkCartClass == 'undefined'){
 var aw_topLinkCartClass = '.top-link-cart';
}
if(typeof aw_addToCartButtonClass == 'undefined'){
 var aw_addToCartButtonClass = '.form-button';
}
if(typeof aw_bigCartClass == 'undefined'){
 var aw_bigCartClass = 
 AW_ACP.theme == 'modern' ?
 '.layout-1column':
 '.col-main';
}


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


if(!$_.ie6){

 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){
 url = getCommonUrl(url)
 
 showProgressAnimation();
 if (type == 'form'){ 
 $_('#product_addtocart_form').action += url; 
 $_('#product_addtocart_form').POST ( 
 function(resp){
 if (typeof(resp) == 'string'){
 try{
 eval('resp = ' + resp);
 }catch(e){
 return obj.form.submit();
 }
 }
 hideProgressAnimation(); 
 if (resp.r != 'success'){
 obj.form.submit();
 }
 else{
 if(AW_ACP.useConfirmation){ 
 showConfirmDialog(); 
 } 
 updateCartView(resp);
 }
 }
 );
 }
 if (type == 'url'){
 $_(url).GET(
 function(resp){
 try{
 if (typeof(resp) == 'string') eval('resp = ' + resp);
 }catch(e){
 win.location.href=url;
 hideProgressAnimation();
 return;
 }
 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));
 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).title = win.$_(aw_topLinkCartClass).innerHTML = resp.links;
}

function updateCartView(resp){
 if (AW_ACP.isCartPage) return updateBigCartView(resp);
 
 var __cartObj = win.$_(aw_cartDivClass);
 if(!__cartObj){
 updateTopLinks(resp);
 return false;
 }
 
 
 if (typeof(__cartObj.length) == 'number') __cartObj = __cartObj[0];
 var oldHeight = __cartObj.offsetHeight;
 
 var tmpDiv = win.document.createElement('div');
 tmpDiv.innerHTML = resp.cart;
 
 var tmpParent = __cartObj.parentNode;
 tmpParent.replaceChild(tmpDiv.firstChild, __cartObj);
 
 /* Details popup support */
 
 var __cartObj = win.$_(aw_cartDivClass);
 if (typeof(__cartObj.length) == 'number') __cartObj = __cartObj[0];
 var newHeight = __cartObj.offsetHeight;
 
 if (aw_ajaxcartpro_cartanim == 'opacity'){
 $_(__cartObj).mutate(
 {opacity:0}, 
 {opacity:1},
 30
 );
 }
 if (aw_ajaxcartpro_cartanim == 'grow'){
 $_(__cartObj).style.overflow = 'hidden';
 $_(__cartObj).mutate( 
 {opacity:0, height: oldHeight + 'px'},
 {opacity:1, height: newHeight + 'px'},
 30
 );
 }
 if (aw_ajaxcartpro_cartanim == 'blink'){
 $_(__cartObj).mutate(
 {opacity:0}, 
 {opacity:1},
 10
 );
 }
 updateDeleteLinks();
 updateTopLinks(resp);
//AW[Deo] Theme fix
 initSlideShow();
 initOpenClose();
 initScrollers();
 initDropDown();
//AW[Deo] Theme fix ends
}

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){ 
 showProgressAnimation();
 url = getCommonUrl(url)
 $_(url).GET(
 function(resp) {
 if (typeof(resp) == 'string') eval('resp = ' + resp);
 hideProgressAnimation();
 updateCartView(resp, '');
 }
 );
}

function showProgressAnimation(){
 var pW = 260;
 var pH = 50;
 p = win.$_('.ajaxcartpro_progress');
 if(typeof p.length == 'number'){
 p = p[0]
 }
 p.style.width = pW + 'px'; 
 p.style.height = pH + 'px';
 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';
}

if(!$_.ie6){
 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;
 } 
 
 // Test for minicart
 
 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)";
 }
 }
}

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

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

var rafDetect = navigator.userAgent.toLowerCase();
var rafOS,rafBrowser,rafVersion,rafTotal,rafThestring;

function rafGetBrowserInfo() {
 if (rafCheckIt('konqueror')) {
 rafBrowser = "Konqueror";
 rafOS = "Linux";
 }
 else if (rafCheckIt('safari')) rafBrowser = "Safari"
 else if (rafCheckIt('omniweb')) rafBrowser = "OmniWeb"
 else if (rafCheckIt('opera')) rafBrowser = "Opera"
 else if (rafCheckIt('webtv')) rafBrowser = "WebTV";
 else if (rafCheckIt('icab')) rafBrowser = "iCab"
 else if (rafCheckIt('msie')) rafBrowser = "Internet Explorer"
 else if (!rafCheckIt('compatible')) {
 rafBrowser = "Netscape Navigator"
 rafVersion = rafDetect.charAt(8);
 }
 else rafBrowser = "An unknown browser";

 if (!rafVersion) rafVersion = rafDetect.charAt(place + rafThestring.length);

 if (!rafOS) {
 if (rafCheckIt('linux')) rafOS = "Linux";
 else if (rafCheckIt('x11')) rafOS = "Unix";
 else if (rafCheckIt('mac')) rafOS = "Mac"
 else if (rafCheckIt('win')) rafOS = "Windows"
 else rafOS = "an unknown operating system";
 }
}

function rafCheckIt(string) {
 place = rafDetect.indexOf(string) + 1;
 rafThestring = string;
 return place;
}

/*-----------------------------------------------------------------------------------------------*/

//Event.observe(window, 'load', rafInitialize, false);
Event.observe(window, 'load', rafGetBrowserInfo, false);
//Event.observe(window, 'unload', Event.unloadCache, false);

var Referafriend = Class.create();
Referafriend.prototype = {
 yPos : 0,
 xPos : 0,
 isLoaded : false,

 initialize: function(ctrl, url) {
 if (url){
 this.content = url;
 } else {
 this.content = ctrl.href;
 }
 ctrl.observe('click', function(event){this.activate();Event.stop(event);}.bind(this));
 $('referafriend').hide().observe('click', (function(event) {if ((event.element().id == 'referafriend-cancel') || (event.element().id == 'span-referafriend-cancel') ) this.deactivate(); }).bind(this));
 },
 
 activate: function(){
 if (rafBrowser == 'Internet Explorer'){
 this.getScroll();
 this.prepareIE('100%', 'hidden');
 this.setScroll(0,0);
 this.hideSelects('hidden');
 }
 this.displayReferafriend("block");
 },
 
 prepareIE: function(height, overflow){
 bod = document.getElementsByTagName('body')[0];
 bod.style.height = height;
 bod.style.overflow = overflow;
 
 htm = document.getElementsByTagName('html')[0];
 htm.style.height = height;
 htm.style.overflow = overflow; 
 },
 
 hideSelects: function(visibility){
 selects = document.getElementsByTagName('select');
 for(i = 0; i < selects.length; i++) {
 selects[i].style.visibility = visibility;
 }
 },
 
 getScroll: function(){
 if (self.pageYOffset) {
 this.yPos = self.pageYOffset;
 } else if (document.documentElement && document.documentElement.scrollTop){
 this.yPos = document.documentElement.scrollTop; 
 } else if (document.body) {
 this.yPos = document.body.scrollTop;
 }
 },
 
 setScroll: function(x, y){
 window.scrollTo(x, y); 
 },
 
 displayReferafriend: function(display){
 $('referafriend-overlay').style.display = display;
 $('referafriend').style.display = display;
 if(display != 'none') this.loadInfo();
 },
 
 loadInfo: function() {
 $('referafriend').className = "loading";
 var myAjax = new Ajax.Request(
 this.content,
 {method: 'post', parameters: "", onComplete: this.processInfo.bindAsEventListener(this)}
 );
 
 },
 
 processInfo: function(response){
 $('rafContent').update(response.responseText);
 $('referafriend').className = "done";
 this.isLoaded = true;
 this.actions();
 },
 
 actions: function(){
 rafActions = $$('rafAction');
 },
 
 deactivate: function(){
 //Element.remove($('rafContent'));
 
 if (rafBrowser == "Internet Explorer"){
 this.setScroll(0,this.yPos);
 this.prepareIE("auto", "auto");
 this.hideSelects("visible");
 }
 
 this.displayReferafriend("none");
 }
}

/*-----------------------------------------------------------------------------------------------*/


function addReferafriendMarkup() {
 bod = document.getElementsByTagName('body')[0];
 overlay = document.createElement('div');
 overlay.id = 'referafriend-overlay';
 raf = document.createElement('div');
 raf.id = 'referafriend';
 raf.className = 'loading';
 raf.innerHTML = '<div id="rafLoadMessage">' +
 '<p>Loading</p>' +
 '</div>';
 bod.appendChild(overlay);
 bod.appendChild(raf);
}

var ReferafriendForm = Class.create();
ReferafriendForm.prototype = {
 initialize: function(form){
 this.form = form;
 if ($(this.form)) {
 this.sendUrl = $(this.form).action;
 $(this.form).observe('submit', function(event){this.send();Event.stop(event);}.bind(this));
 }
 this.loadWaiting = false;
 this.validator = new Validation(this.form);
 this.onSuccess = this.success.bindAsEventListener(this);
 this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
 this.onFailure = this.resetLoadWaiting.bindAsEventListener(this);
 var container = $('invite-login-container');
 if (container && container.style.display == 'none'){
 this._disableEnableAll(container, true);
 }
 },

 send: function(){
 if(!this.validator.validate()) {
 return false;
 }
 this.setLoadWaiting(true);
 var request = new Ajax.Request(
 this.sendUrl,
 {
 method:'post',
 onComplete: this.onComplete,
 onSuccess: this.onSuccess,
 onFailure: this.onFailure,
 parameters: Form.serialize(this.form)
 }
 );
 },
 
 success: function(transport) {
 this.resetLoadWaiting();
 if (transport && transport.responseText){
 try{
 response = eval('(' + transport.responseText + ')');
 }
 catch (e) {
 response = {};
 }
 }
 if (response.error){
 if (response.error_type == 'no_login'){
 var container = $('invite-login-container');
 if (container){
 container.show();
 this._disableEnableAll(container, false);
 }
 }
 if ((typeof response.message) == 'string') {
 alert(response.message);
 } else {
 alert(response.message.join("\n"));
 }
 return false;
 }
 $('rafContent').update(transport.responseText);
 },

 _disableEnableAll: function(element, isDisabled) {
 var descendants = element.descendants();
 for (var k in descendants) {
 descendants[k].disabled = isDisabled;
 }
 element.disabled = isDisabled;
 },

 setLoadWaiting: function(isDisabled) {
 var container = $('invite-button-container');
 if (isDisabled){
 container.setStyle({opacity:.5});
 this._disableEnableAll(container, true);
 Element.show('invite-please-wait');
 this.loadWaiting = true;
 } else {
 container.setStyle({opacity:1});
 this._disableEnableAll(container, false);
 Element.hide('invite-please-wait');
 this.loadWaiting = false;
 }
 },
 
 resetLoadWaiting: function(transport){
 this.setLoadWaiting(false);
 }
}

