var SSS = SSS || {};

if (typeof window.SSS_IE6 == "undefined") {
	var SSS_IE6 = false;
}

if (typeof window.SSS_IE7 == "undefined") {
	var SSS_IE7 = false;
}

SSS.log = true;

function SSS_LOG(txt) {
    if (SSS.log) { console.log(txt); }
}

// fix console so logging works

if (!("console" in window) || !("firebug" in console)) {
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i) {
        window.console[names[i]] = function() {};
    }
}

// add vjustify
jQuery.fn.vjustify=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        $(this).height(maxHeight + "px");
        if (this.offsetHeight>maxHeight) {
            $(this).height((maxHeight-(this.offsetHeight-maxHeight))+"px");
        }
    });
};

jQuery.fn.vcenter=function() {
    var maxHeight=0;
    this.each(function(){
        if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}
    });
    this.each(function(){
        var curr = this.offsetHeight;
        if (curr < maxHeight) {
            var half = Math.floor((maxHeight-curr)/2);
            var img = '<img src="' + SSS.media_url + 'images/tr.gif" height="' + half + '" width="100%" />';
            $(this).height(maxHeight + "px").prepend(img);
        }
        else if (curr > maxHeight) {
             $(this).height((maxHeight-(curr-maxHeight))+"px");
        }
    });
};


// add runOnLoad to handle running methods which need images loaded

function runOnLoad(f) {
    if (runOnLoad.loaded) {
        f();
    }
    else {
        runOnLoad.funcs.push(f);
    }
}

runOnLoad.funcs = [];
runOnLoad.loaded = false;

runOnLoad.run = function() {
    if (runOnLoad.loaded) {
        return;
    }

    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i](); }
        catch(e) { /* pass */ }
    }

    runOnLoad.loaded = true;
    delete runOnLoad.funcs;
    delete runOnLoad.run;
};

if (window.addEventListener) {
    window.addEventListener("load", runOnLoad.run, false);
} else {
    if (window.attachEvent) {
        window.attachEvent("onload", runOnLoad.run);
    }
    else {
        window.onload = runOnLoad.run;
    }
}

// Add methods to SSS

SSS.admin = {

    editable : {},

    add_editable : function(key, link) {
        SSS.admin.editable[key] = link;
    },

    show_edit_links : function() {
        div = '<div id="cmsedit">';
        hit = false;
        for (var label in SSS.admin.editable) {
            div += '<a href="' + SSS.admin.editable[label] + '">Edit ' + label + '</a>';
            hit = true;
        }
        if (hit) {
            div += "</div>";
            $('#ft').append(div);
            SSS_LOG('added edit div');
        }
        else {
            SSS_LOG('no edit div');
        }
    }
};

SSS.bypane = {
    
    curr : "brand-tab",

    page : {
        brand : 0,
        cat : 0,
        sale : 0
    },

    pagecount : {},
    
    init : function() {
		SSS_LOG('init bypane');
		$('td.catcell .whitebox-body').vjustify();
		$("#by-pane ul.tabs img").mouseover(
			function() { SSS.bypane.imageover(this); }
		).each(
			function() { SSS.bypane.preload(this); }
		);
		var panes = Array('brand-list', 'cat-list', 'sale-list');
		for (var i=0; i<panes.length; i++) {
		    SSS.bypane.init_pane(panes[i])
    	}
		SSS.bypane.show_current();
	},
	
	// init a pane group - class is
	// xxx-list, ids are xxx-0, xxx-1, etc.
	init_pane : function(pane) {
	    var panes = $('#by-pane .' + pane);
	    var paneid  = pane.replace('-list', '');
        SSS.bypane.pagecount[paneid] = panes.length;
	},

	imageover : function(elt) {
	    var e = $(elt);
	    var p = e.parent().attr('id');
	    if (p != SSS.bypane.curr) {
	        SSS.bypane.imageout('#' + SSS.bypane.curr + ' img');
    		var img = e.attr('src');
    		e.attr('src', img.replace('_off', '_on'));
		    SSS.bypane.curr = p;
		    SSS.bypane.show_current();
		}
	},

	imageout : function(elt) {
	    var e = $(elt);
    	var img = e.attr('src');
    	e.attr('src', img.replace('_on', '_off'));
	},
	
	preload : function(elt) {
		jQuery("<img>").attr("src", $(elt).attr('src').replace('_off', '_on'));
	},
	
	show_current : function() {
	    var tabid = SSS.bypane.curr;
	    var pageid = tabid.split('-')[0];
	    pageid = pageid.replace("-","");
	    var page = SSS.bypane.page[pageid];

	    var listid = pageid + '-' + page;
	    SSS_LOG('showing ' + listid);
	    $('#by-pane .tab-body').not('#' + listid).hide();
	    $('#' + listid).show();
	    // each(function() {
	    //             
	    //             SSS.bypane.show_or_hide(this, listid);
	    //         });
	},
	
	show_or_hide : function(elt, listid) {
	    var t = $(elt);
        var tid = t.attr('id');
        if (tid != listid) {
            t.hide();
        }
        else {
            t.show()
        }
	},
	
	show_pane_page : function(tab) {
	    var pages = SSS.bypane.pagecount[tab];
	    if (pages > 1) {
	        var pageno = SSS.bypane.page[tab];
	        if (pageno < 0 || pageno >= pages) {
	            SSS.bypane.page[tab] = 0;
	        }
            SSS_LOG(tab + ' page # is ' + pageno)
    	    SSS.bypane.curr = tab + "-tab";
    	    SSS.bypane.show_current()
    	}
	},
	
	show_next_page : function(tab) {
	    SSS_LOG("next: " + tab);
	    SSS.bypane.page[tab]++;
	    SSS.bypane.show_pane_page(tab);
	},
	
	show_prev_page : function(tab) {
	    SSS_LOG("prev: " + tab);
	    SSS.bypane.page[tab]--;
	    SSS.bypane.show_pane_page(tab);
	},

	IETRAP : 'LEAVE ME LAST'
};

SSS.imagemenu = {

	orig : {},
	opened_menu : {},
	leave_open : {},
	rotator_image_class : 'menurotator',

	closeMenu : function(menu) {
		if (menu && menu !== "") {
			menu = $(menu);
			var cls = menu.attr('class');
			var id = menu.attr('id');
			var jid = "#" + id;
			if (SSS.imagemenu.leave_open[cls] != jid) {
				menu.slideUp('normal');

				if (SSS.imagemenu.opened_menu[cls] == jid) {
					SSS.imagemenu.opened_menu[cls] = '';
				}
				$(menu).siblings('.' + SSS.imagemenu.rotator_image_class).attr('src', SSS.imagemenu.rotator_closed_image);
			}
		}
	},

	init : function() {
	    SSS.imagemenu.rotator_opened_image = SSS.media_url + 'images/tri-red-down.gif';
		SSS.imagemenu.rotator_closed_image = SSS.media_url + 'images/tri-red-right.gif';

		SSS_LOG('init imagemenu');
	    SSS.imagemenu.init_process('#sidemenu');
    },

	init_process : function(elt) {
		$(elt + " li a img").hover(
			function() { SSS.imagemenu.imageover(this); },
			function() { SSS.imagemenu.imageout(this); }
		).each(
			function() { SSS.imagemenu.preload(this); }
		);
		//$(elt + ' li.depth1[@class*=cold] ul.depth2').each(
		//	function() { SSS.imagemenu.closeMenu(this); }
		//);
		// open menu and leave open if a child is active
		$(elt + ' li.depth1[@class*=warm] ul.depth2').each(
			function() {
				var menu = $(this);
				SSS.imagemenu.openMenu(menu);
				var id = menu.attr('id');
				SSS_LOG('pre-opened ' + id);
				var cls = menu.attr('class');
				SSS.imagemenu.leave_open[cls] = "#" + id;
			}
		);

	},

	imageover : function(elt) {
		var img = $(elt).attr('src');
		$(elt).attr('src', img.replace(/\/off\//, '/on/'));
	},

	imageout : function(elt) {
		var img = $(elt).attr('src');
		$(elt).attr('src', img.replace(/\/on\//, '/off/'));
	},

	openMenu : function(menu) {
		menu = $(menu);
		var id = menu.attr('id');
		SSS_LOG("opening: " + id);
		var cls = menu.attr('class');
		var curropen = SSS.imagemenu.opened_menu[cls];
		if (curropen != id) {
			SSS_LOG("first closing open menu");
			SSS.imagemenu.closeMenu(curropen);
		}
		if ($.browser.msie) {
		    menu.show();
	    } else {
	    	menu.slideDown('normal');
	    }
		SSS.imagemenu.opened_menu[cls] = '#' + id;
		$(menu).siblings('.' + SSS.imagemenu.rotator_image_class).attr('src', SSS.imagemenu.rotator_opened_image);
	},

	preload : function(elt) {
		jQuery("<img>").attr("src", $(elt).attr('src').replace(/\/off\//, '/on/'));
		jQuery("<img>").attr("src", $(elt).attr('src').replace(/\/off\//, '/curr/'));
	},

	toggleMenu : function(sel) {
		SSS_LOG('toggleMenu: ' + sel);
		var menu = $(sel);
		var cls = menu.attr('class');
		if (SSS.imagemenu.opened_menu[cls] == sel) {
			SSS.imagemenu.closeMenu(menu);
		}
		else {
			SSS.imagemenu.openMenu(menu);
		}
	},

	IETRAP : 'LEAVE ME LAST'
};

SSS.pullmenu = {
	orig : {},
	opened_menu : {},

	closeMenu : function(menu) {
		if (menu && menu !== "") {
			menu = $(menu);
			var cls = menu.attr('class');
			var id = '#' + menu.attr('id');
			menu.children('ul').slideUp('normal');

			if (SSS.pullmenu.opened_menu[cls] == id) {
				SSS.pullmenu.opened_menu[cls] = '';
			}
		}
	},

	init : function(elt) {
		$(elt + " li a img").hover(
			function() { SSS.imagemenu.imageover(this); },
			function() { SSS.imagemenu.imageout(this); }
		).each(
			function() { SSS.imagemenu.preload(this); }
		);
		$(elt + ' ul').hide();
		if ($.browser.mozilla || $.browser.msie) {
		    $(elt + ' ul li').css('margin-bottom', '-3px');
		    $(elt + ' ul li.nudge4').css('margin-bottom', '-4px;');
		}
	},

	openMenu : function(menu) {
		menu = $(menu);
		var id = '#' + menu.attr('id');
		SSS_LOG("opening: " + id);
		var cls = menu.attr('class');
		var curropen = SSS.pullmenu.opened_menu[cls];
		if (curropen != id) {
			SSS_LOG("first closing open menu");
			SSS.pullmenu.closeMenu(curropen);
		}
		menu.children('ul').slideDown('normal');
		SSS.pullmenu.opened_menu[cls] = id;
	},

	toggleMenu : function(sel) {
		SSS_LOG('toggleMenu: ' + sel);
		var menu = $(sel);
		var cls = menu.attr('class');
		if (SSS.pullmenu.opened_menu[cls] == sel) {
			SSS.pullmenu.closeMenu(menu);
		}
		else {
			SSS.pullmenu.openMenu(menu);
		}
	},

	IETRAP : 'LEAVE ME LAST'
};

SSS.centerList = function(sel, offset, outer) {
	var outsz = $(outer).width();
	var sz = 0;
	$(sel).each(function() { sz = sz+$(this).width(); });
	var len = $(sel).length;
	sz = sz + offset*len;
	var shim = Math.floor((outsz-sz)/2);
	$(sel).parent().css('margin-left', shim + 'px');
};

SSS.linkMail = function(sel) {
	$(sel).each(function() {
		SSS.linkMailElement(this);
	});
};

SSS.linkMailElement = function(sel) {
	var elt = $(this);
	var txt = elt.html();
	var lnk = elt.attr('alt') + '@oohgabooga.com';
	elt.html('<a href="mailto:' + lnk + '>' + txt + '</a>');
};

SSS.preloadimages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
};

SSS.cart = {

     showupdating : function(formArray) {
            for (var i = 0; i<formArray.length; i++) {
 			var elt = formArray[i];
 			if (elt.name == 'cartitem') {
 				var itemid = elt.value;
 				$('#status-' + itemid).text('updating');
 			}
 		}
    },

    updatestatus : function(json) {
        success = json.results;
        if (!success) {
            alert(json.errors);
        }
        else {
            var itemid = json.item_id;
            var carttotal = json.cart_total;
            var itemqty = json.item_qty;
            var itemprice = json.item_price;
            var cartitems = json.cart_count;
            $('#form-' + itemid + ' select')[0].value = itemqty;
            var ct = $('#carttotal');
            var currency = ct.text().substring(0,1);
            if (itemqty === 0) {
                $('#itemrow-' + itemid).remove();
            }
            else {
                $('#itemrow-' + itemid + ' .flashing').Highlight(500,'#f9f6ba', function() {
                    $('#status-' + itemid).text('');
                    $('#itemprice-' + itemid).text(currency + itemprice);
                });
            }
            $('.cartfoot').Highlight(500,'#f9f6ba', function() {
                    ct.text(currency + carttotal);
                    $('#cartcount').text(cartitems);
                });
        }
    },

    ZZZ : ''
};

SSS.products = {
	activeimage : "",

	closeup : "",

	imagemap : {},

	imagetgt : "",

	getPrice : function(url) {
    	var options = {
    		url : url,
    		type: 'POST',
    		success : function(json) {
    			name = json[0];
    			price = json[1];
    		    if (name) {
    		        SSS.products.setName(name);
    		    }
    		    SSS.products.setPrice(price);
    		},
    		dataType : 'json'
    	};

    	$('form#options').ajaxSubmit(options);
    },

    setName : function(name) {
        $("#productname").attr('value', name);
    },

    setNamePrice : function(data) {
        name = data[0];
        price = data[1];
        if (name) {
            SSS.products.setName(name);
        }
        SSS.products.setPrice(price);
    },

    setPrice : function(price){
        $("#price").text(price);
    },

	setupImages : function(tgt, thumbs, curr, closeup, suffix, map) {
		SSS.products.activeimage = curr;
		SSS.products.closeup = closeup;
		SSS.products.imagemap = map;
		SSS.products.imagetgt = tgt;
		SSS.products.suffix = suffix;

		$(thumbs).hover(
			function() {
				$(this).addClass('hover');
				SSS.products.showImage(this);
			},

			function() {
				$(this).removeClass('hover');
			});
	},

	showImage : function(elt) {
		var imgobj = SSS.products.imagemap[elt.id];
		var fullurl = imgobj[0];
		var title = imgobj[1];
		var dot = fullurl.lastIndexOf('.');
		var url = fullurl.substring(0,dot) + SSS.products.suffix + fullurl.substring(dot);
		var tgt = $(SSS.products.imagetgt);
		var h = tgt.height();
		tgt.attr({src : url, height : h});
		$(SSS.products.closeup).attr({href : fullurl, title : title});
	},

	ZZZ : ''
};

SSS.products.forms = {

	updatestatus : function(json, result_tgt, count_tgt) {
		var result = json.results;
		if (result == "Success") {
			result = 'ITEM ADDED!';
		}
		$(result_tgt).html(result);
		errors = json.errors;
		if (errors.length > 0) {
			for (var i = 0; i<errors.length; i++) {
				which = errors[i][0];
				err = errors[i][1];
				if (which == 'quantity') {
					$('#label-quantity span.error').html(err);
					SSS_LOG('quantity error:' + err);
				}
				else if (which == 'product') {
					var t = tgt.html();
					tgt.html(t + '<br/>' + err);
					SSS_LOG('Product error: ' + err)
				}
			}
		}
		else {
			var ct = '(' + json.cart_count + ' Item';
			if (json.cart_count != 1) {
				ct = ct + 's';
			}
			ct = ct + ')';
			$(count_tgt).text(ct);
		}
	},

	validate : function(formArray, jqForm, tgt) {
		var qty = 0;
		for (var i = 0; i<formArray.length; i++) {
			var elt = formArray[i];
			if (elt.name == 'quantity') {
				qty = elt.value;
			}
		}
		if (! parseInt(qty)>0) {
			$('#label-quantity span.error').html("Choose a quantity");
			return false;
		}
		return true;
	},

	ZZZ : ''
};

SSS.util = {
    to_currency : function(val) {
		var d = Math.floor(val);
		var c = Math.floor((val*100) % 100);
		if (c < 10) { c = "0" + c; }
		return d + '.' + c;
	},

	preload_rollover : function(elt, suffix) {
	    jQuery("<img>").attr("src", $(elt).attr('src').replace('.' + suffix, '-over.' + suffix));
    },

	rollover : function(elt, state, suffix) {
	    var e = $(elt);
	    var src = e.attr('src');
	    if (!state) {
	        src = src.replace('-over', '');
        }
        else {
            src = src.replace('.' + suffix, '-over.' + suffix);
        }
        e.attr('src', src);
    },

	setup_rollovers : function(val) {
	    $('img.gifrollover').hover(
	        function() { SSS.util.rollover(this, true, 'gif'); },
	        function() { SSS.util.rollover(this, false, 'gif'); }
        ).each(function() {
            SSS.util.preload_rollover(this, 'gif');
        });

        $('img.jpgrollover').hover(
	        function() { SSS.util.rollover(this, true, 'jpg'); },
	        function() { SSS.util.rollover(this, false, 'jpg'); }
        ).each(function() {
            SSS.util.preload_rollover(this, 'jpg');
        });
    },

    ZZZ : ''
};

SSS.fix_authorizenet = function(ct) {
  /*
  var d = $('div.AuthorizeNetSeal img');
  if (d.length == 0) {
    ct++;
    SSS_LOG('fix count ' + ct);
    if (ct < 10) {
      setTimeout(1000, 'SSS.fix_authorizenet("' + SSS.media_url + '", ' + ct + ')');
    }
  }
  SSS_LOG('SSS.fix_authorizenet continuing');
  d.attr({
    src: SSS.media_url + 'images/authorize_net_seal.gif',
    width: '110px', height: '84px'
  }).css('margin-left', '-10px');
  */
};

$(function() {
	$('.search-leaf').click(function() {
		$('#searchform')[0].submit();
	});
	SSS.linkMail('.maillink');
	$('form#user-register input[@type=submit]').click(function() {
		$('form#user-register')[0].submit();
	});
    SSS.imagemenu.init();
});
