var dm = ('https:' == document.location.protocol ? $('base').attr('href').replace('http:', 'https:') : $('base').attr('href'));
function show_cart(){
	if($("#cart").css('display') == 'block'){ $("#cart").slideUp(300).delay(800); } $("#cart").slideDown("slow");
}
function get_cart_item(p, a){	
	var url = "ajaxfun/getCartLastItem/"+p+"/"+a;
	$.ajax({ url: url, type: "GET", dataType: 'json', cache: false, success: function(datas){
			var citem_content;
			if(datas.citem != ''){
				citem_content = '<div id="product_pic"><a href="prods/' + datas.citem.prod_id + '" title=""><img src="' + datas.citem.prod_thumb +'" alt="' + datas.citem.prod_name + '" /></a></div><div id="product_infor"><span class="gray">' + datas.citem.prod_name + '</span><br />' ;
					if(datas.citem.prod_attr != ''){ citem_content += '<span class="black">' + datas.citem.prod_attr + '</span><br />'; }
					citem_content += _ge('cart_item_price') + ' <span>' + datas.citem.prod_price + '</span><br />' + _ge('cart_item_qty') + ' <span class="black">' + datas.citem.prod_qty + '</span>' + '</div>';				
				$('#cart_content').html(citem_content); $('#total_price').html(datas.amt); 
			}
			else{ $('#cart_content').html('<div id="product_infor">' + _ge('cart_no_item') + '</div>'); }
		}
	});	
}
function reload_item_cart(){ var url = "ajaxfun/getCartItemCounts"; $.ajax({ url: url, type: "GET", cache: false, success: function(itm_msg){ $("#citems").html(itm_msg); $("#total_count").html(itm_msg); } }); }
function reload_cart(){ reload_item_cart(); }
function checkLength(o,n,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		return false;
	} else { return true; }
}

//To Validate Tax ID
function ValidateTaxID(sTaxID){
	try{
		var i; var a1, a2, a3, a4, a5; var b1, b2, b3, b4, b5; var c1, c2, c3, c4; var d1, d2, d3, d4, d5, d6, d7; var cd8;
		if(sTaxID.length != 8) return false;
		var c, sum; for (i = 0; i < 8; i++){ c = sTaxID.charAt(i); if ("0123456789".indexOf(c) == -1) return false; }
		d1 = parseInt(sTaxID.charAt(0)); d2 = parseInt(sTaxID.charAt(1)); d3 = parseInt(sTaxID.charAt(2)); d4 = parseInt(sTaxID.charAt(3)); d5 = parseInt(sTaxID.charAt(4)); d6 = parseInt(sTaxID.charAt(5)); d7 = parseInt(sTaxID.charAt(6)); cd8 = parseInt(sTaxID.charAt(7));
		c1 = d1; c2 = d3; c3 = d5; c4 = cd8;
		if((d1 + d2 + d3 + d4 + d5 + d6 + d7 + cd8) == 0){ return false; }
		a1 = parseInt((d2 * 2) / 10); b1 = (d2 * 2) % 10;
		a2 = parseInt((d4 * 2) / 10); b2 = (d4 * 2) % 10;
		a3 = parseInt((d6 * 2) / 10); b3 = (d6 * 2) % 10;		
		a4 = parseInt((d7 * 4) / 10); b4 = (d7 * 4) % 10;		
		a5 = parseInt((a4 + b4) / 10); b5 = (a4 + b4) % 10;
		sum = (a1 + b1 + c1 + a2 + b2 + c2 + a3 + b3 + c3 + a4 + b4 + c4);
		if(sum % 10 == 0) return true;		
		if(d7 = 7){ if((a1 + b1 + c1 + a2 + b2 + c2 + a3 + b3 + c3 + a5 + c4) % 10 == 0) return true; }
		return false;
	}
	catch(e){
		return false;
	}
}

function _do_search(f){
	if(f.keyword.value == f.keyword.alt || f.keyword.value == ''){
		alert(_ge('fill_in_keyword'));
	}
	else{
		var keyword = f.keyword.value.replace(/ /gi, "+");		
		var qsA = ['q='+encodeURIComponent(keyword)];
		if (f.c.value) qsA.push('c='+encodeURIComponent(f.c.value));
		
		var surl = f.action+'search/index/?'+qsA.join('&');
		document.location = surl;		
	}
	return ;	
}

function _dosubscribe(){
	if($('#newsletter_email').val() != '' && $('#newsletter_email').val() != $('#newsletter_email').attr('title')){		
		if($('#newsletter_name').val() == $('#newsletter_name').attr('title')){ $('#newsletter_name').val(''); }
		var post_url = dm+'/mailing/subscription';
		$.post(post_url, $("#frmNewsletter").serialize(), function(result){ showMsg(_ge('newsletter'), result.msg); }, 'json');	
	}
	else{ showMsg(_ge('newsletter'), _ge('msg_email_required')); }
}

function showMsg(title, msg){	
	if(title.length == 0){ $("#errMsg").prev().find('span.ui-dialog-title').html(""); } else { $("#errMsg").dialog({ title: title }); }
	if(msg != '') $("#errMsg").html(msg);	
	openDialog();
}
function openDialog(){
	var buttons = {};
	buttons[_ge('closed')] = function() { $(this).focus().dialog('close'); };
	$("#errMsg").dialog({
		autoOpen: false, width: 400, resizable: false, modal: true, buttons: buttons,
		open: function() { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); }	
	});	
	//open
	$("#errMsg").dialog('open');	
	$('#errMsg').next().find('button:first').focus();
}

function showConfirmMsg(title, msg, link){	
	//init
	if(msg != '') $("#errMsg").html(msg);
	if(title != '') $("#errMsg").dialog({ title: title });	
	var buttons = {};	
	buttons[_ge('confirm')] = function() { $(this).focus().dialog('close');if( typeof(link['confirm'])!='undefined' ) location.href = link['confirm']; };
	buttons[_ge('cancel')] = function() { $(this).focus().dialog('close');if( typeof(link['cancel'])!='undefined' ) location.href = link['cancel']; };
	$("#errMsg").dialog({
		autoOpen: false,
		width: 400,		
		resizable: false,
		modal: true,		
		buttons: buttons,		
		open: function() {
					$(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();
			  }
	});	
	//open
	$("#errMsg").dialog('open');	
	$('#errMsg').next().find('button:first').focus();
}

function showMsgJumpToLink(title, msg, link){	
	//init
	if(msg != '') $("#errMsg").html(msg);
	if(title != '') $("#errMsg").dialog({ title: title });
	
	
	var buttons = {};
	buttons[_ge('closed')] = function() { $(this).focus().dialog('close'); location.href = link; };
	$("#errMsg").dialog({
		autoOpen: false,
		width: 400,		
		resizable: false,
		modal: true,		
		buttons: buttons,
		open: function() {
					$(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();
			  },
		destory: function(){
				location.href = link;				
				return false;
			},
		close: function(){
				location.href = link;				
				return false;
			}
	});	
	//open
	$("#errMsg").dialog('open');	
	$('#errMsg').next().find('button:first').focus();
}

// Include certain jquery easing style:
jQuery.extend(jQuery.easing,{
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	}
});

// For Drop Down Menu Effect: (2011-02-17)
$.fn.hoverIntent= function(f,g) {
    var cfg={sensitivity:7,interval:100,timeout:0};
    cfg=$.extend(cfg,g?{over:f,out:g}:f);
    var cX,cY,pX,pY;
    var track= function(ev) {
        cX=ev.pageX;
        cY=ev.pageY;
    };
    var compare= function(ev,ob) {
        ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
        if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity) {
            $(ob).unbind("mousemove",track);
            ob.hoverIntent_s=1;
            return cfg.over.apply(ob,[ev]);
        } else {
            pX=cX;
            pY=cY;
            ob.hoverIntent_t=setTimeout( function() {
                compare(ev,ob);
            },cfg.interval);
        }
    };
    var delay= function(ev,ob) {
        ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
        ob.hoverIntent_s=0;
        return cfg.out.apply(ob,[ev]);
    };
    var handleHover= function(e) {
        var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;
        while(p&&p!=this) {
            try {
                p=p.parentNode;
            } catch(e) {
                p=this;
            }
        }
        if(p==this) {
            return false;
        }
        var ev=jQuery.extend({},e);
        var ob=this;
        if(ob.hoverIntent_t) {
            ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);
        }
        if(e.type=="mouseover") {
            pX=ev.pageX;
            pY=ev.pageY;
            $(ob).bind("mousemove",track);
            if(ob.hoverIntent_s!=1) {
                ob.hoverIntent_t=setTimeout( function() {
                    compare(ev,ob);
                },cfg.interval);
            }
        } else {
            $(ob).unbind("mousemove",track);
            if(ob.hoverIntent_s==1) {
                ob.hoverIntent_t=setTimeout( function() {
                    delay(ev,ob);
                },cfg.timeout);
            }
        }
    };
    return this.mouseover(handleHover).mouseout(handleHover);
};

$.fn.touched = function(speed, onhover, offhover){
	$(this).bind('mouseenter', function(){ $(this).animate({'opacity': onhover},{'duration':speed}) });
	$(this).bind('mouseleave', function(){ $(this).animate({'opacity':offhover},{'duration':speed}) });
	return this;
};

$(window).load(function(){
});

$(function(){	
	$(document).click(function(e) { if (e.button == 0) { $("#cart").slideUp(300); } });
	// Search
	// $('.global-search-submit').mouseover(function(){ $(this).css('cursor', 'pointer'); }).mouseout(function(){ $(this).css('cursor', ''); });
	
	$('input[name="keyword"]').each(function(){
		$(this).click(function(){
			if($(this).val()===$(this).attr('alt')){
				$(this).val('');
			}
			$(this).css('color', '#555');
		}).blur(function(){
			if($(this).val().length === 0 ){
				$(this).val($(this).attr('alt'));
			}
			$(this).css('color', '#999');
		});										
	});

	/* cart items */
	$('#mini_cart').live('mouseover mouseleave', function(event){if(event.type == 'mouseover'){$(this).find('span').removeClass();}else{$(this).find('span').removeClass();}});reload_cart(); 
	/* shopping cart */
	$('#close').click(function(){ document.getElementById("cart").style.display = "none"; });	
		
	$("a").click(function(event) {						  		
		if($(this).attr('class').match(/popup-(\d+)-(\d+)/)){
			event.preventDefault();
			var B = $(this).attr('class').match(/popup-(\d+)-(\d+)/);
			if(B){l=B[1]; B=B[2];}else{B=l=450;}
			window.open($(this).attr('href'),'popup',"scrollbars=yes,location=0,statusbar=0,menubar=0,width="+l+",height="+B).focus();
		}				
	});
	
  if( $('.astro-attached').val() != '' && $('.astro-attached').val() != $('.astro-attached').attr('title') ){
				$('.attached-astro').hide();
  }

	$('input').click(function(){
		if($(this).val() == $(this).attr('title')){
				$(this).val('');
				if( $(this).is('.astro-attached') ){
					$('.attached-astro').hide();
				}
    }
	}).blur(function(){
		if($(this).val() == ''){
				$(this).val($(this).attr('title'));
				if( $(this).is('.astro-attached') ){
					$('.attached-astro').show();
				}
				}
	})

	$('.dropdown').hoverIntent({
		timeout: 200,
		over: function(){
			if($.browser.msie && $.browser.version==7){
			$('.intop').css('margin-top',0).slideDown('fast');
			}else{
			$('.intop').slideDown('fast');
			}
			$('.dropstart').addClass('mouseon');
		},
		out: function(){
			if($.browser.msie && $.browser.version==7){
			$('.intop').slideUp('fast');
			}else{
			$('.intop').slideUp('fast');
			}
			$('.dropstart').removeClass('mouseon');
		}
	});

	$('.cate_box_list').find('li:not(".level2")').bind('mouseenter mouseleave', function(){
		$(this).toggleClass('hov');
	});
	
  // Execute 'go-to-top' anchor
	$('#go-to-top').show();
	$('#go-to-top').click(function(){
		$('html, body').animate({'scrollTop' : -10}, {
					'duration':900,
					'easing':'easeOutExpo',
					'queue':false,
					'complete':function(){
					$('#go-to-top').show();}
		});
		$(this).hide();
		return false;
	});

	// Trigger the brand lists scroller in 2011 new header
	$('#brand_logos').cycle({
		'fx': 'scrollHorz',
		'speed': 750,
		'timeout': 0,
		'pause': 1,
		'random': 1,
		'prev': '#brand_scroll_left',
		'next': '#brand_scroll_right',
		'onPrevNextEvent' : function(isNext, Index, slideElement) {
			$('.brand_list_pager ol li').removeClass('ac').eq( Index ).addClass('ac'); //品牌專館Scroll Index 
		},
		'slideExpr': 'div.group'
	});
	$('#brand_scroll').css('visibility', 'visible');  
	
	$('.news_scroll').cycle({
		 fx: 'scrollDown',
		 speed: '400',
		 timeout: '5000',
		 slideExpr: 'a',
		 pause: '1'
	});
	
	$('.sub_header_news').css('visibility', 'visible');
	
	$('.scroll_arr').css('opacity', 0.5).touched(200, 1, 0.5);
	
	if($("#errMsg").html() != "") openDialog();
	
	$('#errMsg input').keyup(function(e) {
		if (e.keyCode == 13) {
			$('#errMsg').find('button:first').click();
		}
	});
	$('#verifyPWDdialog input').keyup(function(e) {
		if (e.keyCode == 13) {
			$('#verifyPWDdialog').next().find('button:first').click();
		}
	});
});


(function() {
  //var proxied = window.alert;
  alert_old = window.alert;
  window.alert = function( msg ) {
    // do something here	
	//console.log('', arguments);	
	if( document.getElementById('errMsg') == null )
	{
		alert_old( msg );
	}
	else
	{
		document.getElementById('errMsg').innerHTML = msg;
		var buttons = {};
		buttons[ _ge('closed') ] = function() { $(this).focus().dialog('close'); };
		
		$("#errMsg").dialog({
			autoOpen: false,
			width: 400,		
			resizable: false,
			modal: true,		
			buttons: buttons,
			open: function() { $(this).parents('.ui-dialog-buttonpane button:eq(0)').focus(); }
		});	
		//open
		$("#errMsg").dialog('open');
	}
  };  
})();
