var SSS = SSS || {};

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

if (typeof window.SSS_IE == "undefined") {
	var SSS_IE = 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");
        }
    });
};

// add vcenter
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] + '" target="_blank">Edit ' + label + '</a>';
            hit = true;
        }
        if (hit) {
            div += "</div>";
            $('#ft').append(div);
            SSS_LOG('added edit div ');
        }
    }
};

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') + '@farinaz.com';
	elt.html('<a href="mailto:' + lnk + '>' + txt + '</a>');
};

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 : "",
	
	preloads : {},
	
	setupImages : function(tgt, thumbs, curr, closeup, map) {
		SSS.products.activeimage = curr;
		SSS.products.closeup = closeup;
		SSS.products.imagemap = map;
		SSS.products.imagetgt = tgt;

		var doc = $('#bd');
		for (var img in map) {
		    var url = map[img][1];
            var elt = jQuery('<img src="' + url + '" class="preload">');
            SSS.products.preloads[img] = elt;
            doc.append(elt);
		}

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

			function() {
				$(this).removeClass('hover');
			}).click(function() { 	
			    SSS.products.showImage(this);
			});
	},

	showImage : function(elt) {
		var imgobj = SSS.products.imagemap[elt.id];
		var fullurl = imgobj[0]
		var url = imgobj[1];
		var title = imgobj[2];
		var tgt = $(SSS.products.imagetgt);
		var loaded = SSS.products.preloads[elt.id];
	    var h = loaded.height();
	    var w = loaded.width();
	    SSS_LOG('new ' + elt.id + ' h=' + h + ' w=' + w);
		tgt.attr('src', url)
		tgt.attr('height', h);
		tgt.attr('width', w);
		tgt.css({height: h+'px', width: w+'px'});
		
		var zhref = SSS.products.imagemap[elt.id][0];
		var zoomtgt = $(SSS.products.imagetgt + "outer");
		zoomtgt.attr('href', zhref);
		SSS_LOG('updated href to: ' + zhref);
		//$(SSS.products.closeup).attr({href : url, title : title});
	},

	ZZZ : ''
};

SSS.util = {
    preloadimages : function() {
        var base = "";
        for(var i = 0; i<arguments.length; i++) {
            if (i == 0 && arguments.length > 1) {
                base = arguments[i];
            }
            else {
                jQuery("<img>").attr("src", base + arguments[i]);
            }
        }
    },
    
    to_currency : function(val) {
		var d = Math.floor(val);
		var c = (val*100) % 100;
		if (c < 10) { c = "0" + c; }
		return d + '.' + c;
	},

    ZZZ : ''
};

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

