$.fn.opacity = function(amount) { if (amount > 1) amount = 1;
    if (amount < 0) amount = 0;
    if ($.browser.msie) {
        amount = (parseFloat(amount) * 100);
        this.css('filter', 'alpha(opacity='+amount+')');
    } else {
        this.css('opacity', amount);
        this.css('-moz-opacity', amount);
    }
    return this;
}
//------------------------------------------------------------------------------
    String.prototype.htmlEntities=function(){
        return this.replace(/&/g,'&amp;').
                    replace(/</g,'&lt;').
                    replace(/>/g,'&gt;').
                    replace(/'/g,'&#039;').
                    replace(/"/g,'&quot;')};
//------------------------------------------------------------------------------
    String.prototype.htmlDecode=function(){
        return this.replace(/\\&#039;/g, "'").
                    replace(/\\&quot;/g, '"').
                    replace(/\\\\/g, "\\")};
//------------------------------------------------------------------------------
    String.prototype.titleize=function(){
        var w=this.split(' ');
        for(var i=0;i<w.length;i++){w[i]=w[i].charAt(0).toUpperCase()+
                                              w[i].substring(1).toLowerCase()}
        return w.join(" ").replace("&amp;","&").
                           replace("&Amp;","&").
                           replace("&Reg;","&reg;").
                           replace("&Copy;","&copy;")}
//------------------------------------------------------------------------------
$.textMetrics = function(el) {
    var h = 0, w = 0;
    var div = document.createElement('div');
    document.body.appendChild(div);
    $(div).css({
        position: 'absolute',
        left: -1000,
        top: -1000,
        display: 'none'
    });
    $(div).html($(el).html());
    var styles = ['font-size',
                  'font-style',
                  'font-weight',
                  'font-family',
                  'line-height',
                  'text-transform',
                  'letter-spacing'];
    $(styles).each(function() {
        var s = this.toString();
        $(div).css({s: $(el).css(s)})});
    h = $(div).outerHeight();
    w = $(div).outerWidth();
    $(div).remove();
    return {
        height: h,
        width: w
    };
}
//------------------------------------------------------------------------------
var base = {};
    base.form = {};
    base.html = {};
//------------------------------------------------------------------------------
base.form.submit = function(c) {
    $("input[rel=add_product_button]").attr("disabled",c);
};
//------------------------------------------------------------------------------
base.form.add = function(id) {
    base.form.submit(true);
    setTimeout('base.form.submit(false)',10000);
    $("#"+id).submit();
    return false;
}  ;
//------------------------------------------------------------------------------
base.ajax = function(opts){
    var _json,
		url = window.location;

    $.ajax({
        type: "POST",
        url: url.protocol+"//"+url.hostname+pages['ajax_controller'],
        data: opts,
        dataType : "json",
        cache: false,
        timeout: 15000,
        error: function(e){},
        beforeSend: function(){},
        success: function(){},
        complete: function(ajaxData){
            _json = eval('('+$.trim(ajaxData.responseText)+')');
            switch(opts.action){
                case "render_gallery":
                    base.html.gallery.renderGallery(_json);
                    break;
                case "get_position_discount_info":
                	base.html.jaaspeel.setMsg(_json);
                	break;
                case "get_welcome_msg":
                    base.html.welcomeMsg.setMsg($.extend(_json,opts));
                default:break;
            }
        }
    })
};
//------------------------------------------------------------------------------
base.url = {
    getParams : function( url, key ) {
        url.match(/\?(.+)$/);
        var params = RegExp.$1;
            params = params.split("&");
        var queryStringList = {},
            res;
        for(var i=0;i<params.length;i++) {
            var tmp = params[i].split("=");
            queryStringList[tmp[0]] = unescape(tmp[1])
        }
        res = typeof queryStringList[key] == "undefined" ? undefined : queryStringList[key].split("#")[0];
        return res;
    }
};

base.keepalive = {
    timeout: 20 * 60 * 1000,

    init: function() {
        setTimeout("base.keepalive.keepAlive()", this.timeout);
    },

    keepAlive : function() {
        var url = window.location;

        $.ajax({
            type: "POST",
            url: pages['ajax_controller'],
            data: {
                'action' : 'keep_alive'
            },
            dataType : "json",
            cache: false,
            timeout: this.timeout,
            complete: function(data) {
                setTimeout("base.keepalive.keepAlive()",  this.timeout);
            }
        });
    }
}

//------------------------------------------------------------------------------
base.html = {
//------------------------------------------------------------------------------
    carouselToggle : function(opts) {
        opts = opts || {};
        $('.topSellers').find('ul').slideDown(1000);
        $("div.carousel").carousel({
            dispItems: opts.items || 7,
            autoSlide:opts.slide ||  true,
            autoSlideInterval: opts.interval || 5000,
            delayAutoSlide: opts.delay || 2000
        });
    },
//------------------------------------------------------------------------------
    expressShipping : function() {
        $(".expressShippingHover").hover(
            function(){
                $(this).next().toggle("fast");
            }
        );
    },
//------------------------------------------------------------------------------
    moveTop : function(s){$("html,body").scrollTo($(".wrapper"),s)},
//------------------------------------------------------------------------------
    scrolls : function(c){
        var hide=c?"auto":"hidden";
        $('html').css({overflowY:hide, overflowX:'hidden'});
        //$('body').css({overflowY:hide, overflowX:'hidden'});
    },
//------------------------------------------------------------------------------
    ie6selects : function(c){
        var hide=c?"visible":"hidden";
        $.each($("select"),function(){
            if ($.browser.msie &&
                $.browser.version == "6.0") {$(this).css("visibility",hide)}});
    },
//------------------------------------------------------------------------------
    setHTMLOpacity : function(opts) {
        var winWidth  = this.gallery.getSize('sw'),
            winHeight = this.gallery.getSize('sh'),
            shadow    = $('<div id="'+this.gallery.shadowID+'"></div>');

        this.scrolls(false);

        if (shadow.length>0) shadow.remove();
        if (typeof opts.transparency == "undefined") {
            opts.transparency = this.gallery.transparency;
        }

        shadow.css({zIndex         :1000,
                    backgroundColor:opts.bgcolor,
                    position       :"absolute",
                    left           :0,
                    top            :0,
                    width          :winWidth*2,
                    height         :winHeight*20}).opacity(opts.transparency);

        shadow.appendTo('body');
    }
};
//------------------------------------------------------------------------------
base.html.getWidth = function(item,outer){
    var wl,wr;
    wl = parseInt($(item).css(outer+'Left'),10);
    wr = parseInt($(item).css(outer+'Right'),10);
    return wl+wr;
};
//-----------------------------reset by id selector------------------------------------
base.html.resetNavbar = function(id, type){
	var nav = $("#"+id);
    
    if (nav.length == 0) {
        return;
    }
    var navWidth = nav.width(),
        lis      = nav.find('li'),
        liSize   = lis.length,
        items    = {},
        realWidth= 0,
        defWidth = 0,
        li,p,m,delta;
    $.each(lis, function(k,v){
        p = base.html.getWidth($(v),'padding');
        m = base.html.getWidth($(v),'margin');
        items[k]={
            item  : $(v),
            text  : $(v).text(),
            length: $(v).text().length,
            size  : $.textMetrics($(v))}
        realWidth += $.textMetrics($(this)).width+(p+m);
        $(v).find('a').css({width:'auto'})});
    $.each(items, function(k,v){
        delta = navWidth-realWidth;
        v.item.css({width : Math.floor(v.size.width+delta/liSize)});
        defWidth += Math.floor(v.size.width+delta/liSize)});
    li = items[liSize-1].item;
    p = base.html.getWidth(li,'padding');
    m = base.html.getWidth(li,'margin');
    li.css({width : navWidth-defWidth+Math.floor(items[liSize-1].size.width+delta/liSize)-(p+m)*liSize});
    nav.show();
};
//-----------------------------reset by class selector--------------------------------
base.html.resetNavbarClass = function(cl){
	var nav = $("."+cl);
    
    if (nav.length == 0) {
        return;
    }
    var navWidth = nav.width(),
        lis      = nav.find('li'),
        liSize   = lis.length,
        items    = {},
        realWidth= 0,
        defWidth = 0,
        li,p,m,delta;
    $.each(lis, function(k,v){
        p = base.html.getWidth($(v),'padding');
        m = base.html.getWidth($(v),'margin');
        items[k]={
            item  : $(v),
            text  : $(v).text(),
            length: $(v).text().length,
            size  : $.textMetrics($(v))}
        realWidth += $.textMetrics($(this)).width+(p+m);
        $(v).find('a').css({width:'auto'})});
    $.each(items, function(k,v){
        delta = navWidth-realWidth;
        v.item.css({width : Math.floor(v.size.width+delta/liSize)});
        defWidth += Math.floor(v.size.width+delta/liSize)});
    li = items[liSize-1].item;
    p = base.html.getWidth(li,'padding');
    m = base.html.getWidth(li,'margin');
    li.css({width : navWidth-defWidth+Math.floor(items[liSize-1].size.width+delta/liSize)-(p+m)*liSize});
    nav.show();
};
//-----------------------------reset by ANY selector--------------------------------
base.html.resetNavbarSelector = function(sel){
	var nav = $(sel);
    
    if (nav.length == 0) {
        return;
    }
    var navWidth = nav.width(),
        lis      = nav.find('li'),
        liSize   = lis.length,
        items    = {},
        realWidth= 0,
        defWidth = 0,
        li,p,m,delta;
    $.each(lis, function(k,v){
        p = base.html.getWidth($(v),'padding');
        m = base.html.getWidth($(v),'margin');
        items[k]={
            item  : $(v),
            text  : $(v).text(),
            length: $(v).text().length,
            size  : $.textMetrics($(v))}
        realWidth += $.textMetrics($(this)).width+(p+m);
        $(v).find('a').css({width:'auto'})});
    $.each(items, function(k,v){
        delta = navWidth-realWidth;
        v.item.css({width : Math.floor(v.size.width+delta/liSize)});
        defWidth += Math.floor(v.size.width+delta/liSize)});
    li = items[liSize-1].item;
    p = base.html.getWidth(li,'padding');
    m = base.html.getWidth(li,'margin');
    li.css({width : navWidth-defWidth+Math.floor(items[liSize-1].size.width+delta/liSize)-(p+m)*liSize});
    nav.show();
};
//------------------------------------------------------------------------------
base.html.imgCaption = function(c){
	var d;
	$("img."+c).each(function(){
		d=$(".figure");
		$(this).wrap('<div class="figure" style="position:relative;"></div>').
				after('<p class="caption" style="display:none;position:absolute;bottom:0;left:0;width:94%;margin:0;padding:5px 3%;">'+
					  $(this).attr("title")+'</p>').
				removeAttr('title')});
	d.width($(this).find('img').width());
	d.mouseenter(function(){$(this).find('p.caption').slideToggle()}).
	  mouseleave(function(){$(this).find('p.caption').slideToggle()});
}
//------------------------------------------------------------------------------
base.html.gallery = {
    shadowID    : 'shadow_container',
    speed       : 500,
    margin      : 50,
    transparency: 0.5,
    resetOpacity: 1,
    params      : {},
//------------------------------------------------------------------------------
    getSize : function(s){
        var _res;
        switch(s) {
            case 'sh':
                _res = screen.height;
                break;
            case 'sw':
                _res = screen.width;
                break;
            case 'wh':
                _res = $(window).height();
                break;
            case 'ww':
                _res = $(window).width();
                break;
        }
        return _res;
    },
//------------------------------------------------------------------------------
    setGalleryPosition : function(p){
        this.params.position=p;
        base.ajax(this.params);
        this.params.position=0;
    },
//------------------------------------------------------------------------------
    createFlash : function(opts){
		opts.url		= "/images/template_"+opts.template+"/preview.swf";
		opts.id			= "flashcontent";
		opts.w			= "725";
		opts.h			= "544";
		opts.flashvars  = {product_id: opts.product_id};
		opts.attributes = {
			id  : "sotester",
			name: "sotester"};
		base.html.flash.renderFlash(opts);
    },
//------------------------------------------------------------------------------
    renderGallery : function(opts){

        if(opts.allowed==0) return;

        $("#"+this.shadowID).remove();

        var gc        = $("#"+opts.container_id),
            margin    = this.margin,
            winHeight = this.getSize('sh'),
            html      = base.html;

        html.moveTop(300);

        if (gc.length>0) gc.remove();

        html.ie6selects(false);
        html.setHTMLOpacity(opts);

        $('body').append(opts.html);

        var obj          = $("#"+opts.container_id),
            objWidth     = obj.width(),
            objHeight    = obj.height();

        var offsetWidth  = this.getSize('ww')/2 - objWidth/2;
            offsetWidth  = offsetWidth <= margin ? margin : offsetWidth;
        var offsetHeight = winHeight/2 - objHeight/2 - margin;
            offsetHeight = offsetHeight <= margin ? margin : offsetHeight;

        obj.css({top     :offsetHeight-margin/2,
                 left    :offsetWidth,
                 position:'absolute',
                 zIndex  :parseInt($("#"+this.shadowID).css("zIndex"),10)+1}).
                 										opacity(this.resetOpacity);
		this.createFlash(opts);
        $("#"+opts.container_id).fadeIn(this.speed);
    },
//------------------------------------------------------------------------------
    closeGallery : function(e){
        var html=base.html;
        html.ie6selects(true);
        html.scrolls(true);
        $("#"+this.shadowID).remove();
        $(e).parent().remove();
    }
};
//------------------------------------------------------------------------------
base.html.welcomeMsg = {
    container_id: 'welcome_container',
    bgcolor     : '#000000',
    action      : 'get_welcome_msg',
    delay       : 60000,
    transparency: .4,
    visible     : 0,
//------------------------------------------------------------------------------
    show : function(opts){
        opts                = opts              || {};
        opts['visible']     = opts.visible      || this.visible;
        opts['visible']     = parseInt(opts['visible'],10);

        opts['container_id']= opts.container_id || this.container_id;
        opts['bgcolor']     = opts.bgcolor      || this.bgcolor;
        opts['delay']       = opts.delay        || this.delay;
        opts['action']      = opts.action       || this.action;
        opts['transparency']= opts.transparency || this.transparency;

        if (opts['visible']==1) {
            var allowedURL = window.location.pathname;
            if (this.checkCookie()) {
                if (!$.cookie('welcome')&&
                    (allowedURL=='/')) {
                    base.ajax(opts);
                } else {
                    $.cookie('welcome', 1, {expires: 365, path: '/'});
                }
            }
        }
    },
//------------------------------------------------------------------------------
    hideMsg : function() {
        $("#"+base.html.gallery.shadowID).remove();
        base.html.ie6selects(true);
        base.html.scrolls(true);
		$("#"+this.container_id).remove();
    },
//------------------------------------------------------------------------------
    setMsg : function(opts){
        this.hideMsg(opts.container_id);
	    if(opts.enabled==0) return;
        $('body').append(opts.html);
    	var div = $("#"+opts.container_id).css({position: 'absolute'});
	    base.html.moveTop(300);
	    base.html.jaaspeel.alignMsg(opts);
	    base.html.ie6selects(false);
	    base.html.setHTMLOpacity(opts);
	    div.show();
	    setTimeout('base.html.welcomeMsg.hideMsg()',opts.delay);
        $.cookie('welcome', 1, {expires: 365, path: '/'});
    },
//------------------------------------------------------------------------------
    checkCookie : function(){
        return typeof $.cookie == 'function';
    }
//------------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
base.html.flash = {
//------------------------------------------------------------------------------
    renderFlash : function(opts){
        var flashvars  = opts.flashvars||{},
            attributes = opts.attributes||{},
            params     = {
                allowFullScreen	 :'false',
				allowScriptAccess:'always',
                scale			 :'noscale',
                menu			 :'false',
                wmode			 :'transparent',
				quality			 :'high',
				bgcolor			 :opts.bgcolor||''
            };

        swfobject.embedSWF(opts.url,
                           opts.id,
                           opts.w,
                           opts.h,
                           "9.0.0",
                           "js/expressInstall.swf",
                           flashvars,
                           params,
                           attributes);
    }
};
//------------------------------------------------------------------------------
base.html.jaaspeel = {
//------------------------------------------------------------------------------
	renderCurl : function() {
		$("#pageflip").hover(function() {
			$("#pageflip img , .msg_block").stop()
				.animate({
					queue: 'false',
					duration: '3000',
					width: '500px',
					height: '500px'
				}, 500);
			} , function() {
			$("#pageflip img").stop()
				.animate({
					width: '73px',
					height: '76px'
				}, 220);
			$(".msg_block").stop()
				.animate({
					width: '73px',
					height: '73px'
				}, 200);
		});
	},
//------------------------------------------------------------------------------
	click : function(){base.ajax({action:'get_position_discount_info'})},
//------------------------------------------------------------------------------
	setMsg : function(msg){
		if(msg.length>0) {
			this.showMsg({
				bgcolor		:'#000000',
				allowed		:1,
				text        :msg.join("\n"),
				container_id:'peel_container'});
		}
	},
//------------------------------------------------------------------------------
	hideMsg	: function(id){
        var html=base.html;
        $("#"+html.gallery.shadowID).remove();
        html.ie6selects(true);
        html.scrolls(true);
		$("#"+id).hide();
	},
//------------------------------------------------------------------------------
	alignMsg : function(opts){
        var obj          = $("#"+opts.container_id),
        	objWidth     = obj.width(),
        	objHeight    = obj.height();

	    var offsetWidth  = base.html.gallery.getSize('ww'),
	    	offsetHeight = base.html.gallery.getSize('wh');

	    var centerX = offsetWidth/2,
	    	centerY = offsetHeight/2;

	    obj.css({
	    	top: centerY - objHeight/2 + 'px',
	    	left: centerX - objWidth/2 + 'px'
	    });
	},
//------------------------------------------------------------------------------
	showMsg	: function(opts){
        this.hideMsg(opts.container_id);
	    if(opts.allowed==0) return;
    	var html = base.html,
    		div  = $("#"+opts.container_id);
	    if(opts.delay==null)opts.delay=60000;
	    html.moveTop(300);
	    this.alignMsg(opts);
	    html.ie6selects(false);
	    html.setHTMLOpacity(opts);
	    $("#peel_note_msgs").html(opts.text);
	    div.show();
	    setTimeout('base.html.jaaspeel.hideMsg("'+opts.container_id+'")',opts.delay);
	},
//------------------------------------------------------------------------------
	setCss : function(w,h){$("#msg_container_peel").css({width:w,height:h})}
};

base.html.loadMenu = {
   loadedMenus: [],
   load:function(menuid)
   {
       if ($("#"+menuid).length !== 0 && this.loadedMenus[menuid] == undefined) {
            this.loadedMenus[menuid]= 1;
            base.html.resetNavbar(menuid);
        }
    },
	loadLeftMenu:function(menuid){
		if( $("#"+menuid).length !== 0 && this.loadedMenus[menuid] == undefined){
		  $("#"+menuid).webwidget_vertical_menu({
                    directory: "images/template_{/literal}{$template}{literal}"
           });
			this.loadedMenus[menuid]= 1;
		}

	}
};
//------------------------------------------------------------------------------
base.html.tip = {
//------------------------------------------------------------------------------
    init : function(e){
        $(e).bind("mouseenter", this.createTip);
		$(e).mouseleave(function(){$("#tip").remove()});
		$(e).click(function(){$("#tip").remove()});
        $(e).mousemove(function(e){$("#tip").css({left:e.pageX+30,
                                                  top :e.pageY-16})});
    },
//------------------------------------------------------------------------------
    createTip : function(e) {
        var obj=$(e.currentTarget),
            title=$.trim(obj.attr("helper"));
        if(title.length>0){
            return $("#tip").length === 0 ?
        		$("<div>").html("<span>"+$.trim(obj.attr("helper"))+
                                "</span><span class='arrow'></span>").
                           attr("id","tip").
                           css({left			:e.pageX+30,
                                top				:e.pageY-16,
                                position		:'absolute',
                                border			:'1px solid #FFE222',
                                backgroundColor	:'#FFFBC2',
                                color			:'#514721',
                                padding			:'5px 10px',
                                textTransform	:'lowercase',
                                fontVariant		:'small-caps',
                                zIndex			:9000}).
                           appendTo("body") : null;
        } else {return false}
    }
//------------------------------------------------------------------------------
};
//------------------------------------------------------------------------------
$(document).ready(function(){
    base.html.expressShipping();
    base.keepalive.init();
});
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// jQuery Popup Bubble
//------------------------------------------------------------------------------



$(document).ready(function(){
    $(".bubble-popup a").hover(function() {
    $(this).next(".bubble-popup-box").stop(true, true).animate({opacity: "show", top: "30"}, "slow");
    }, function() {
    $(this).next(".bubble-popup-box").animate({opacity: "hide", top: "40"}, "fast");
    });
	/***IE6**/

});
$(window).load(function(){

	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		if($.cookie('ie6_cookie')!="WeNotSupportingIE698h32kjns"){
			$.cookie('ie6_cookie', 'WeNotSupportingIE698h32kjns');
			$.fancybox({
				/*'width': '550px',*/
				/*'height': '340',*/
				'autoScale': true,
				'transitionIn': 'fade',
				'transitionOut': 'fade',
				'type': 'iframe',
				'href': 'js/ie-6/ie-6.html'
			});
		};
	};
	$("#fancybox-content").css("border","none");
	$("#fancybox-wrap").css("width","562px")
});

