/* -------------------------*/
/* Wishlist
/* -------------------------*/

function addToShoppinglist(productId, x, y) {

	$j('#addtoshoppinglist_message').hide();
	$j('#addtoshoppinglist_message_txt').html($j('#addtoshoppinglist_message_loading').html());
	pop('#addtoshoppinglist_message', x, y);

	idarr = productId.split('_');

	var url = (("https:" == document.location.protocol) ? "/shoppinglist/secureadd/index" : "/shoppinglist/add/index");
	$j.ajax({
		type: "POST",
		url: url,
		dataType: "json",
		data: "product="+idarr[0]+'&child='+idarr[1],
		success: function(msg){
			$j('#addtoshoppinglist_message_txt').html(msg.message);

		}
	});
}

function pop(id,x,y) {
	var sh = $j(window).height();
	var scrollTop = $j(window).scrollTop();
	var ih = $j(id).height();

	var top = y

	y = y - scrollTop;

	if (y+ih > sh) {
		top = sh - ih - 60 + scrollTop;
	}

	if (top < 0) {
		top = 0 + scrollTop;
	}

	//$(id).css("z-index","8000");
	$j(id).css("top",top + "px");
	$j(id).css("left",x + "px");
	$j(id).fadeIn("slow");
}

function hidepop(id) {
	$j(id).fadeOut("slow");
}

/* -------------------------*/
/* Account Menu
/* -------------------------*/
$j(document).ready(function() {
	$j(".account-header-menu").hover(
		function () {
			$j("#account-header-menu").show();
		},
		function () {
			$j("#account-header-menu").hide();
		}
		);

	//login
	$j(".account-heder-login").hover(
		function () {
			$j(".login-popup").show();
		}
		);

	$j('.account-header-login-close').click(function() {
		$j(".login-popup").hide();
	});
	
	$j('#login_popup_form input').live('keyup',function(e) {
		if (e.keyCode == 13) {
			$j('#login_popup_form').submit();
		}
	});
});


/* -------------------------*/
/* Navigation bar
/* -------------------------*//**
var CAT_COOKIE_OPTIONS = { path: '/' };
var clicked_cats = {};
var arr = new Array();
var exclude_cat_id = '';
var opensubnav1 = '';
var opensubnav2 = '';

function setExcludeCatId(id) {
	exclude_cat_id = id;
}

$j(document).ready(function() {
        
    initNavigation();
        
    $j('.parent-level0').click(function() {
        var id = $j(this).attr('id').replace('nav-','');
        //console.log('id: ' + id);
        //console.log('exclude_cat_id: ' + exclude_cat_id);
        if (id != exclude_cat_id) {
            $j('.subnav-' + opensubnav2).hide();
            opensubnav2 = opensubnav1;
            //console.log('opensubnav2: ' + opensubnav2);
            $j('.subnav-' + id).show();
            opensubnav1 = id;
            //console.log('opensubnav1: ' + opensubnav1);
        }
        setCategoryCookie(id);
	});

	$j(".sub-nav").children("ul").children("li").hover(
		function () {
			$j(this).addClass("hover");			
		},
		function () {
			$j(this).removeClass("hover");
		}
		);

	$j(".show_subs").mouseover(
		function (event) {
			var cat_id = $j(this).attr('id');
			var sub_nav_id = '#sm_' + cat_id.replace('cat_','');
			if ($j(sub_nav_id).length > 0) {
				var offset = $j(this).offset();
				var top_offset = offset.top - $j(window).scrollTop();

				// plus 6 above is for the border at the bottom of the sub-nav
				var diff = Math.floor($j(sub_nav_id).outerHeight() + top_offset - $j(window).height()) + 6;

				if (diff > 0) {
					$j(sub_nav_id).attr('style','top:-' + diff + 'px');
				} else {
					$j(sub_nav_id).attr('style','top:-20px');
				}
			}
		}
		);
});
*/
/**
 * Initialize left navigation when page loads
 * Hide all expanded sub-categories in category page (because of cached left nav)
 * Category pages: Expand current category if user is in cagtegory page
 * Product page: use cookie to expand sub categories
 *//**
function initNavigation(){
    //console.log('initNavigation() called..');
    if (location.pathname == '/') { // homepage hide all sub categories
        //$j('div#navigation ul li ul.sub-nav').hide();
        $j.cookie('cats');
        $j.cookie('curr_cat');
        return;
    }
    
    $j('div#navigation ul li ul.sub-nav').hide(); // hide all when page is loaded.
    var curr_cat = $j('input[name=curr_category]:hidden').val();
    //console.log('curr_cat: ' + curr_cat);
    if (curr_cat != undefined) { //console.log(1); // in product page
        $j.cookie('curr_cat', curr_cat, CAT_COOKIE_OPTIONS);
        $j('.subnav-' + curr_cat).show(); // expand current category
        opensubnav1 = curr_cat;
    } else { //console.log(2);
        if ($j.cookie('cats') != null) { // in category page
            
            var cats = $j.cookie('cats').split(/,/);
            console.log('cats in category page: ' + cats.toSource());
            
            for (var i=0; i<cats.length; i++) {
                $j('.subnav-' + cats[i]).show();
                window['opensubnav' + (i + 1)] = cats[i];                
            }
            if ($j.cookie('curr_cat') != null) {
                $j.cookie('curr_cat', null, CAT_COOKIE_OPTIONS);
            }
        }
    }    
}

function setCategoryCookie(cat){
    //$j('.subnav-' + cat).show(); // always show clicked category..
    clicked_cats = getCategoryCookies();
    //console.log('cat: ' + cat);
    //console.log('cats: ' + clicked_cats.toSource());
    
    if (clicked_cats[cat]) {
        delete clicked_cats.cat;
    }
    clicked_cats[cat] = 1;
    var i = 0;
    for (var key in clicked_cats) {
        arr[i] = key;
        i++;
    }
    
    var last_two_elem = (arr.length - 2);
    arr_sliced = arr.slice(last_two_elem);
    
    //console.log('arr: ' + arr.toSource());
    //console.log('size: ' + arr.length + ', last_two_elem: ' + last_two_elem + ', (last_two_elem - 1): ' + (last_two_elem - 1));
    
    //for (var j=0; j<(last_two_elem - 1); j++) {
        //$j('.subnav-' + arr[j]).hide();
    //}   
    
    arr_sliced.reverse();
    //console.log('arr sliced: ' + arr_sliced.reverse().toSource());
    $j.cookie('cats', arr_sliced, CAT_COOKIE_OPTIONS);
    
    //if ($j.cookie('cats') != null) {
        //console.log("$j.cookie('cats'): " + $j.cookie('cats').toSource());
    //}
}

function getCategoryCookies(){
    if ($j.cookie('cats') == null) {
        return {};
    } else {
        var str_stored_cats = $j.cookie('cats');
        arr_stored_cats = str_stored_cats.split(/,/);
        //console.log('arr_stored_cats: ' + arr_stored_cats.toSource());
        clicked_cats = {};
        for (var i=0; i<arr_stored_cats.length; i++) {
            clicked_cats[arr_stored_cats[i]] = 1;
        }    
        return clicked_cats;
    }
}
*/

/**
 * In homepage 2 categories can be expanded.
 * In category page, 2 categories plus current category can be expanded.
 * jquery cookie has been used to save categories
 */
var Navigation = Class.create();
Navigation.prototype = {

    initialize: function() {
        this.NUM_EXPAND = 2;
        this.COOKIE_OPTIONS = { path: '/' };
        this.cats = { cat_1: '', cat_2: '', current: '' };
    },
    
    run: function() {
        var nav = this; // since we can't use 'this' inside event listener 
        var arr = [];
        $j('li.parent-level0').bind('click', function() {
            var cat = $j(this).attr('id').replace('nav-', '');
            arr = nav.getCatsFromCookie(); 
            if (arr.length < nav.NUM_EXPAND){
                if (!nav.in_array(cat, arr)) {
                    arr[arr.length] = cat;
                }
            } else {
                if (!nav.in_array(cat, arr)) {
                    var shifted = arr.shift();
                    $j('.subnav-' + shifted).hide();
                    arr[arr.length] = cat;
                }
            }
            for(var i=0; i<nav.NUM_EXPAND; i++) {
                $j('.subnav-' + arr[i]).show();
                nav.cats['cat_' + (i+1)] = arr[i];
            }
            nav.setCookie('cats', nav.cats);
            nav.showCurrentCategory();
        });
        if (this.isHomepage()) {
            this.setCookie('cats', null);
        }
        this.expandAllCats();
    },
    
    getCookie: function(key) {
        return $j.evalJSON($j.cookie(key));
    },

    setCookie: function(key, value) {
        $j.cookie(key, $j.toJSON(value), this.COOKIE_OPTIONS);
    },
    
    getCatsFromCookie: function() {
        var _cats = [];
        var cookieCats = this.getCookie('cats');
        if (cookieCats) {
            for (var c in cookieCats) {
                if (cookieCats[c]) {
                    if (!this.in_array(cookieCats[c], _cats)) {
                        _cats[_cats.length] = cookieCats[c];
                    }
                }
            }
        }  
        return _cats;
    },
    
    getCatFromPath: function() {
        var path = location.pathname.replace(/^\//, ''); // remove slash '/' at the begining
        var paths = path.split('/');
        return paths[0];
    },

    showCurrentCategory: function() {
        var _cat = this.getCatFromPath();
        if (_cat) {
            $j('.subnav-' + _cat).show();
        }
    },

    isHomepage: function() {
        return this.getCatFromPath() ? false : true;
    },

    in_array: function(val, arr) {// check if element does not exist in array
        for (var i=0; i < arr.length; i++) {
            if (arr[i] == val) {
                return true;
            }
        }
        return false;
    },
    
    expandAllCats: function() {        
        if (this.getCookie('cats') != null) {
            var cookieCats = this.getCookie('cats');
            for (var key in cookieCats) {        
                if (cookieCats[key]) {
                    $j('.subnav-' + cookieCats[key]).show();
                }
            }
        }    
        this.showCurrentCategory();
    }
    
};

$j(document).ready(function() {
    
    new Navigation().run();
    
    $j(".sub-nav").children("ul").children("li").hover(
		function () {
			$j(this).addClass("hover");			
		},
		function () {
			$j(this).removeClass("hover");
		}
    );

	$j(".show_subs").mouseover(
		function (event) {
			var cat_id = $j(this).attr('id');
			var sub_nav_id = '#sm_' + cat_id.replace('cat_','');
			if ($j(sub_nav_id).length > 0) {
				var offset = $j(this).offset();
				var top_offset = offset.top - $j(window).scrollTop();

				// plus 6 above is for the border at the bottom of the sub-nav
				var diff = Math.floor($j(sub_nav_id).outerHeight() + top_offset - $j(window).height()) + 6;

				if (diff > 0) {
					$j(sub_nav_id).attr('style','top:-' + diff + 'px');
				} else {
					$j(sub_nav_id).attr('style','top:-20px');
				}
			}
		}
    );
    
});

/* -------------------------*/
/* Begin		    */
/* Recently viewed products */
/* -------------------------*/
var COOKIE_NAME="dcrecprod";
var OPTIONS = {
	path: '/',
	expires: 10
};
var recently_viewed = new Array();
var max_products=10;
var viewed_products=3;
var just_add=false;
function addRecentProduct(name, image, url, id){
	var products = getRecentProducts();
	var saved_products = getRecentProducts();
	var arr_length = products.length;
	for (var i = 0; i < arr_length; i++) {
		if (products[i].url == url) {
			saved_products.splice(i,1);
		}
	}
	var product = new Acaproduct(name,image,url,id);
	saved_products.push(product);
	if(saved_products.length>=max_products){
		saved_products.shift();
	}
	just_add=true;
	var cookie_string = $j.base64Encode($j.toJSON(saved_products));
	$j.cookie(COOKIE_NAME, cookie_string, OPTIONS);
}
function removeRecentProducts(ids) {
	var products = getRecentProducts();
	var arr_length = products.length;
	var new_arr = Array();
	for (var i = arr_length-1; i >=0; i--) {
		if (jQuery.inArray(products[i].id, ids) != -1 || (ids.length==1 && products[i].id!=ids)) {
			new_arr.push(products[i]);
		}
	}

	var cookie_string = $j.base64Encode($j.toJSON(new_arr));
	$j.cookie(COOKIE_NAME, cookie_string, OPTIONS);
}
function getRecentProducts(){
	var cookie_string=$j.cookie(COOKIE_NAME);
	if(cookie_string!==null){
		var recently_viewed = eval($j.base64Decode(cookie_string));
		return recently_viewed;
	}
	else
	{
		return new Array();
	}
}
function clearRecentProducts(){
	$j.cookie(COOKIE_NAME, null, OPTIONS);
}
function Acaproduct(name, image, url, id){
	this.name=name;
	this.image=image;
	this.url=url;
	this.id=id
}
function loadProducts(num_prods){
	var products=getRecentProducts();
	var arr_length = products.length;
	var code = '';

	if (arr_length==0||(arr_length==1 && just_add)) {
		$j('#recently-viewed-products').hide();
	}
	else {
		var dec=1;
		if (just_add) dec=2;
		count=1;
		for (i=arr_length-dec; i >= 0 && (count<=viewed_products); i--) {
			code += "<div class=\"line\"><div class=\"image\"><a href=\""+products[i].url+"\"><img src=\""+products[i].image+"\" alt=\""+products[i].name+"\" /></a></div><div class=\"info\"><a href=\""+products[i].url+"\">"+products[i].name+"</a></div><div class=\"clear\">&nbsp;</div></div>";
			count++;
		}

		$j('#rec_view').html(code);
	}
}
/* -------------------------*/
/* End				   */
/* Recently viewed products */
/* -------------------------*/

/* -------------------------*/
/* Ajax add to cart */
/* -------------------------*/
var Addtocart = Class.create();
Addtocart.prototype = {
	initialize: function(form, params, saveUrl){
		this.form = form;
		if ($(this.form)) {
			$(this.form).observe('submit', function(event){
				this.save();
				Event.stop(event);
			}.bind(this));
		}
		if (saveUrl=='') {
			saveUrl='addAjax';
		}
		var ajax_url = (("https:" == document.location.protocol) ? "/dcheckout/securecart/"+saveUrl+"?" + params : "/dcheckout/cart/"+saveUrl+"?" + params);
		this.saveUrl = ajax_url;
		this.validator = new Validation(this.form);
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.onFailure = this.failure.bindAsEventListener(this);
		this.is_valid = false;
	},

	validate: function() {
		this.is_valid = this.validator.validate();
		return this.is_valid;
	},

	save: function(){

		if (this.validate()) {
			$j('.addtocart_button').hide();
			$j('.addtocart_loading').show();
			var request = new Ajax.Request(
				this.saveUrl,
				{
					method:'post',
					onSuccess: this.onSave,
					onFailure: this.onFailure,
					parameters: Form.serialize(this.form)
				}
				);
		}
	},

	nextStep: function(transport){
		if (transport && transport.responseText){
			try{
				response = eval('(' + transport.responseText + ')');
			}
			catch (e) {
				response = {};
			}
		}
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		$j('#'+this.form)[0].reset();

		if (response.r=='failure') {
			showCartSidebar();
			$j('#cart_sidebar_messages').html(response.messages);

		} else {
			$j('#cart_sidebar').html(response.html);
			removeRecentProducts(response.ids);
		}

	},

	failure: function(transport){
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		alert("Error submitting add to cart request");
	}
}

var Addtocartmin = Class.create();
Addtocartmin.prototype = {
	initialize: function(form, params, saveUrl){
		this.form = form;
		if ($(this.form)) {
			$(this.form).observe('submit', function(event){
				this.save();
				Event.stop(event);
			}.bind(this));
		}
		if (saveUrl=='') {
			saveUrl='addAjax';
		}
		var ajax_url = (("https:" == document.location.protocol) ? "/dcheckout/securecart/"+saveUrl+"?" + params : "/dcheckout/cart/"+saveUrl+"?" + params);
		this.saveUrl = ajax_url;
		this.validator = new Validation(this.form);
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.onFailure = this.failure.bindAsEventListener(this);
		this.is_valid = false;
	},

	validate: function() {
		this.is_valid = this.validator.validate();
		return this.is_valid;
	},

	save: function(){

		if (this.validate()) {
			$j('.addtocart_loading').show();
			$j('.addtocart_btn').hide();

			$j('#addtocart_message_txt').html('');
			$j('#addtocart_message_loading').show();

			var request = new Ajax.Request(
				this.saveUrl,
				{
					method:'post',
					onSuccess: this.onSave,
					onFailure: this.onFailure,
					parameters: Form.serialize(this.form)
				}
				);
		}
	},

	nextStep: function(transport){
		if (transport && transport.responseText){
			try{
				response = eval('(' + transport.responseText + ')');
			}
			catch (e) {
				response = {};
			}
		}
		$j('#addtocart_message_loading').hide();
		$j('.addtocart_loading').hide();
		$j('.addtocart_btn').show();


		if (response.r=='failure') {
			$j('#addtocart_message_txt').html(response.messages);
		}
		else if (response.r=='success') {
			$j('#addtocart_message_txt').html('Product successfully added to your cart.');
			$j('#'+this.form)[0].reset();
		}
		else {
			$j('#addtocart_message_txt').html('An error occurred. Please try again.');
		}

		addtocartmessage_timeoutID = window.setTimeout(hideaddtocartmessage, 2000);

	},

	failure: function(transport){
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		alert("Error submitting add to cart request");
	}
}

function hideaddtocartmessage() {
	$j('#addtocart_message').fadeOut();
}

/* -------------------------*/
/* Ajax estimate shipping   */
/* -------------------------*/
var estimateShipping = Class.create();
estimateShipping.prototype = {
	initialize: function(form, params, saveUrl){
		this.form = form;
		if ($(this.form)) {
			$(this.form).observe('submit', function(event){
				this.save();
				Event.stop(event);
			}.bind(this));
		}
		if (saveUrl=='') {
			saveUrl='estimateShipping';
		}
		var ajax_url = (("https:" == document.location.protocol) ? "/dcheckout/securecart/"+saveUrl+"?" + params : "/dcheckout/cart/"+saveUrl+"?" + params);
		this.saveUrl = ajax_url;
		this.validator = new Validation(this.form);
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.onFailure = this.failure.bindAsEventListener(this);
		this.is_valid = false;
	},

	validate: function() {
		this.is_valid = this.validator.validate();
		return this.is_valid;
	},

	save: function(){

		if (this.validate()) {
			$j('#estimate-shipping-submit').hide();
			$j('#estimate-shipping-submit-waiting').show();

			var request = new Ajax.Request(
				this.saveUrl,
				{
					method:'post',
					onSuccess: this.onSave,
					onFailure: this.onFailure,
					parameters: Form.serialize(this.form)
				}
				);
		}
	},

	nextStep: function(transport){
		if (transport && transport.responseText){
			try{
				response = eval('(' + transport.responseText + ')');
			}
			catch (e) {
				response = {};
			}
		}
	   
		if (response.r=='failure') {
			showCartSidebar();
			$j('#cart_sidebar_messages').html(response.messages);

		} else {
			$j('#cart_sidebar').html(response.html);
		}
		$j('#estimate-shipping-submit').show();
		$j('#estimate-shipping-submit-waiting').hide();

	},

	failure: function(transport){
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		alert("Error submitting add to cart request");
	}
}


/* -------------------------*/
/* Quickorder add to cart */
/* -------------------------*/
var Quickorder = Class.create();
Quickorder.prototype = {
	initialize: function(form, params, saveUrl){
		this.form = form;
		if ($(this.form)) {
			$(this.form).observe('submit', function(event){
				this.save();
				Event.stop(event);
			}.bind(this));
		}
		if (saveUrl=='') {
			saveUrl='addAjax';
		}
		var ajax_url = (("https:" == document.location.protocol) ? "/dcheckout/securecart/"+saveUrl+"?" + params : "/dcheckout/cart/"+saveUrl+"?" + params);
		this.saveUrl = ajax_url;
		this.validator = new Validation(this.form);
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.onFailure = this.failure.bindAsEventListener(this);
		this.is_valid = false;
	},

	validate: function() {
		this.is_valid = this.validator.validate();
		return this.is_valid;
	},

	save: function(){

		if (this.validate()) {
			$j('.addtocart_button').hide();
			$j('.addtocart_loading').show();
			var request = new Ajax.Request(
				this.saveUrl,
				{
					method:'post',
					onSuccess: this.onSave,
					onFailure: this.onFailure,
					parameters: Form.serialize(this.form)
				}
				);
		}
	},

	nextStep: function(transport){
		if (transport && transport.responseText){
			try{
				response = eval('(' + transport.responseText + ')');
			}
			catch (e) {
				response = {};
			}
		}
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		$j('#'+this.form)[0].reset();

		if (response.r=='failure') {
			showCartSidebar();
			$j('#cart_sidebar_messages').html(response.messages);

		} else {
			$j('#cart_sidebar').html(response.html);
			resetTable();
		}

	},

	failure: function(transport){
		$j('.addtocart_button').show();
		$j('.addtocart_loading').hide();
		alert("Error submitting add to cart request");
	}
}



