var scrollNum = 0;
var countdownSec = 10;

function cur(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
//return (((sign)?'':'-') + '$' + num + '.' + cents);
var rtn= (((sign)?'':'-') + num);
if (rtn=="-0")
	return "0";
else
	return rtn;
}

function IsInt(s)
{
    for (var i=0;i<s.length;i++){   
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    return true;
}

function registerBookmark()
{
	if (document.all || window.sidebar)
		$("#favSpan").show();
	else
		$("#favSpan").hide();

	$("#btnAddBookmark").live("click", function(){
		
		try
		{
			bookmarkurl="http://www.veryhit.com";
			bookmarktitle="Veryhit.com 換物網";

			if (document.all)
			{
				window.external.AddFavorite(bookmarkurl,bookmarktitle)
			}
			else if (window.sidebar) // firefox
			{
				window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
			}
		}
		catch (err){}
	});
}

function queryString(name) 
{ 
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); 
  var regexS = "[\\?&]"+name+"=([^&#]*)"; 
  var regex = new RegExp(regexS); 
  var results = regex.exec( window.location.href ); 
  if (results==null) return ""; 
  return decodeURIComponent(results[1].replace(/\+/g, " ")); 
} 

function goTo(addr)
{
	document.location = addr;
}

function scrollTop()
{
	scroll(0,0);
}

function scrollBottom()
{
	setTimeout("goBottom()", 500);
}

function goBottom()
{
	window.scrollTo(0, document.body.scrollHeight);
}

function changeLang(lang)
{
	var url = document.location;
	url = url+"";
	for (var i =1;i!=10;i++)
		url = url.replace("#t"+i, ""); //tabs
	url = url.replace("#", "");
	
	current = queryString("lang");
	if (current!="" && current!=null) //modify
	{
		url = url.replace("lang="+current, "lang="+lang);
		document.location = url;
	}
	else
	{
		
		if (url.indexOf("?")>-1)
		{
			url = url + "&lang=" + lang
			document.location = url;
		}
		else
		{
			url = url + "?lang="+lang;
			document.location = url;
		}
	}
}

$.support.shadow = (function(){
     var me = document.body || document.documentElement,
	 mystyle = me.style,
	 supportShadow = 
	 mystyle.mozBoxShadow !== undefined ||
	 mystyle.webKitBoxShadow !== undefined || 
	 mystyle.boxShadow !== undefined;
	 return supportShadow;
 })();

function blinkImg(time, classname, interval){
     var timer = window.setInterval(function(){ 
		 $(classname).css("opacity", "0.5"); 
		 window.setTimeout(function(){  
			$(classname).css("opacity", "1");   
		 }, 200);
		}, interval); 
	 window.setTimeout(function(){clearInterval(timer);}, time);
 } 
 
 function trim(s)
 {
	return s.trim();
 }

String.prototype.trim = function() 
{ 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 

String.prototype.endsWith = function(str) 
{ 
    var lastIndex = this.lastIndexOf(str); 
    return (lastIndex != -1) && (lastIndex + str.length == this.length); 
}

String.prototype.endsWith = function(str) 
{   var lastIndex = this.lastIndexOf(str);     
	return (lastIndex != -1) && (lastIndex + str.length == this.length); 
}
function setmouseover(obj)
{
	if( document.createEvent ) {
		var evObj = document.createEvent('MouseEvents'); 
		evObj.initEvent( 'mouseover', true, false );
		obj.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
		obj.fireEvent('onmouseover');        
	}
}
//MAIN SIMPLE MENU HL
function menuHighlight()
{
	var loc = window.location + "";
	loc = loc.trim();
	
	$(".mihover").each(function(){
		var l = $(this).parent().attr("href");
		
		if (typeof(bIndex) === 'undefined') {
		//do nothing
		}
		else if (bIndex)
		{
			changeMenuTab($("#home"));
			return false;
		}
		
		if (loc.indexOf("article.php")>-1)
		{
			changeMenuTab($("#blog"));
			return false;
		}
		
		if (loc.indexOf(l)>0)
		{
			changeMenuTab($(this));
			return false;
		}
	 });
}

function changeMenuTab(obj)
{
	var src = obj.attr("src");
	src = src.replace("_off.gif", "_on.gif");
	src = src.replace("boxmenu_", "boxmenu2_");
	
	obj.attr("src", src);
	obj.addClass("activeMenuitem")
}

function scrollToElement(element)
{
	$('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'fast', easing: 'swing'});
	
	//$(element).css("background", "#ccc")
}


function scrollToElementAtFAQPage(element)
{
	$('html,body').animate({ scrollTop: $(element).offset().top }, { duration: 'fast', easing: 'swing'});
	$(".faqAns").css("background", "#F7F7F7")
	$(".faqAns").css("color", "#000")
	$(element).css("background", "#eee")
	$(element).css("color", "#0000ff")
}

function menuScroll()
{
   
   $('.sideBarDiv').scrollFollow({
	delay:300,
	speed:500
   });
}

function cursorWait()
{
	$("body").css("cursor", "wait");
}

function cursorDefault()
{
	$("body").css("cursor", "default");
}

function addSpliter()
{
	$(".ui-state-default-new").each(function() {
		if (!$(this).hasClass("lb"))
		{	
			if ($(this).html().indexOf("titlebarsp")==-1) //not added
			{
				var orgWidth = $(this).width();
				$(this).html("<div class=titlebarsp style='width:" +(orgWidth-10) + "px'>" +$(this).html()+ "</div>");
			}
		}
	});	
}

function scrollToTop()
{	
	if (IsAdvanceBrowser())
		$('html, body').animate( { scrollTop: 0 },250);
	else
		scrollTop();
}

function prepareIcon()
{
	if ($(".scrollable").length>0)
		$(".scrollable").scrollable({ vertical: true, mousewheel: true, circular: true }).autoscroll({interval:4000});
}

function simpleHover()
{
	$(".xmhover").mouseover(function(){
		if (!$(this).hasClass("activeMenuitem"))
		{
			var src = $(this).attr("src");
			
			src = src.replace("m2", "m1"); //maybe the active one
			src = src.replace("_off.gif", "_on.gif");
			
			$(this).attr("src", src);
		}
	}).mouseout(function(){
		if (!$(this).hasClass("activeMenuitem"))
		{
			var src = $(this).attr("src");
			src = src.replace("_on.gif", "_off.gif");
			$(this).attr("src", src);
		}
	});
}

function fixHeader()
{
	if ($('.shadowTable').length>0)
		$('.shadowTable').fixedtableheader(); 
}
	
function hoverImg()
{
	simpleHover();

	$(".mihover").mouseover(function(){
		if (!$(this).hasClass("activeMenuitem"))
		{
			var src = $(this).attr("src");
			
			src = src.replace("m2", "m1"); //maybe the active one
			src = src.replace("_off.gif", "_on.gif");
			
			$(this).attr("src", src);
		}
	}).mouseout(function(){
		if (!$(this).hasClass("activeMenuitem"))
		{
			var src = $(this).attr("src");
			src = src.replace("_on.gif", "_off.gif");
			$(this).attr("src", src);
		}
	});
	
	$("#vhnImg").mouseover(function(){
		$(this).attr("src", "images/enlogosmallcolor.gif");
	}).mouseout(function(){
		$(this).attr("src", "images/enlogosmall.gif");
	});
	$("#kfImg").mouseover(function(){
		$(this).attr("src", "images/KFnew2.gif");
	}).mouseout(function(){
		$(this).attr("src", "images/KFnew.gif");
	});
	$("#btnMoreRequestItem").mouseover(function(){
		$(this).attr("src", "images/down_2hover.gif");
	}).mouseout(function(){
		$(this).attr("src", "images/down_2.gif");
	})
	$("#btnCloseMoreRequestItem").mouseover(function(){
		$(this).attr("src", "images/close_2hover.gif");		
	}).mouseout(function(){
		$(this).attr("src", "images/close_2.gif");
	})
	
	$(".removeX").mouseover(function(){
		$(this).attr("src", "images/close_2redhover.gif");		
	}).mouseout(function(){
		$(this).attr("src", "images/close_2.gif");
	})	
}

function IsIDevice()
{
	return (navigator.userAgent.indexOf("iPhone")>-1 || navigator.userAgent.indexOf("iPad")>-1);
}

function IsAdvanceIE()
{
	return ($.browser.msie && $.browser.version.substr(0,1)>=9);
}

function IsIE6()
{
	return ($.browser.msie && $.browser.version.substr(0,1)<7);
}

function escapeHtml(unsafe) {  
	return unsafe.replace(/&/g, "&amp;")
				.replace(/</g, "&lt;")
				.replace(/>/g, "&gt;")
				.replace(/"/g, "&quot;")
				.replace(/'/g, "&#039;");
}

function IsAdvanceBrowser()
{
	if (navigator.userAgent.indexOf("Chrome")>-1) return true;
	return ((IsAdvanceIE() || $.browser.webkit || navigator.userAgent.indexOf("Firefox/4")) && !$.browser.opera && navigator.userAgent.indexOf("Safari")==-1);
}
//IE6DBMGFIX
jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

// ...and use it to overcome the 'double margin' bug. Add display:inline to all floated elements
function doubleMarginFix() {
	$(':regex(css:float, left|right)').css('display', 'inline');
}
//END OF IE6DBMGFIX
function ie6layoutFix()
{
	$(".commentline").each(function(){
		$(this).parent().height( $(this).height() );
	});
}

function renderCode()
{
/*
	$("code").each(function(){
		var htm = $(this).html();
		$(this).text( htm );
		$(this).append("<BR>");
	});		*/
	$(".code").each(function(){
		var htm = $(this).html();
		var cObj = $(this);
		
		htm = htm.replace("<PRE>", "");
		htm = htm.replace("<pre>", "");
		htm = htm.replace("</PRE>", "");
		htm = htm.replace("</pre>", "");


		var tmpCode = htm.replace(/[<>]/g, function(m) { return {'<':'&lt;','>':'&gt;'}[m]});
		tmpCode = tmpCode.trim();
		tmpCode = tmpCode.replace(/&lt; /g, "&lt;");
		tmpCode = tmpCode.replace(/&gt; /g, "&gt;");
		
		tmpCode = tmpCode.replace(/&lt;/g, "<span style='color:brown'>&lt;");
		tmpCode = tmpCode.replace(/&gt;/g, "&gt;</span>");
		
		tmpCode = tmpCode.replace(/&lt;!/g, "<span class=comment>&lt;!");
		tmpCode = tmpCode.replace(/--&gt;/g, "--&gt;</span>");
		
		
		tmpCode = tmpCode.replace(/\/\*/g, "<span class=comment>/*");
		tmpCode = tmpCode.replace(/\*\//g, "*/</span>");
						
		$(cObj).html("");
		$(cObj).append("<pre style='letter-spacing:0px;font-family:courier new,san-serif !important;font-size:12px;border:1px solid #ccc;background:#fff;margin:10px;padding:10px;margin-left:0px;'>"+tmpCode+"</pre>");
		$(cObj).css("clear", "both");
	});
}

function makeShortName()
{
	$(".pluginName").each(function(){
		var html = $(this).html();
		var typeIdfk = $(this).attr("typeIdfk");
		
		if (typeIdfk==5)
		{
			html = html.replace("jquery plugin - ", "");
			if (html.length>20)
				html = html.substring(0,19) + "..";
				
			$(this).html(html);
		}
	});
}

function hideVisitor()
{
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	if (is_chrome)
	{
		$("#visitCounter").css("position", "absolute");
		$("#visitCounter").css("top", -1000);
	}
}

function qrCode()
{
	$("#mobileVersion").MyQRCode({content:"http://kfsoft.info/m", size:"130x130"});
}

function detectMobile()
{
	var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
    if (mobile) { 
		$("#mobileDiv").css("fontWeight", "bold");
		$("#mobileDiv").css("color", "#ff2200");
		
	}
	
}

$(function(){
	qrCode();
	detectMobile();
	
	hideVisitor();
	prepareIcon();
	hoverImg();
	fixHeader();
	renderCode();
	makeShortName();
	
	$("input:button").addClass('button');
	$("input[type=text], input[type=password]").addClass('tbox');
	$("textarea").addClass('tabox');

	menuHighlight();
	menuScroll();

	if ($.browser.msie && $.browser.version.substr(0,1)<7)
	{
		$(document).pngFix();
        
		$("#newsBox").prepend('<div id="noIe6Div" style="display:none;padding-left:20px;padding-top:10px;padding-right:10px;float:right;color:#bbb"> * 重要提示: 你正在使用ie6，我們不完全支援ie6，請使用新版ie或其他瀏覽器 * </div>'); 
		$("#noIe6Div").slideDown();
	}

	//Cufon.replace('a',{ fontFamily: 'Lacuna Regular', fontSize:'12px', hover: { color: 'black', fontWeight: 'bold'} });
});
