// JavaScript Document
 
// setting
basepath="/Content",
xpath = {
	loader: basepath+"/Scripts",
	img: basepath+"/Images/zh-HK",
	api: basepath+"/Api",
	flv: basepath+"/Uploads",
	videoData: "/zh-HK/Videos",
	adbox: basepath+"/Uploads/Adbox/zh-HK",
	spotlight: basepath+"/Spotlight_form/tc"
}
url = window.location.href;
len_path = url.length;
path_id = url.lastIndexOf("/tc/");
path = url.substring(0, path_id);
latesttab="";
latestajax=null;
var smonthName=["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
var cookieSetting = { expires: 366*2, path:"/" }


$(document).ready(function () {
	
	$(":text").css({"border-color":"#cccccc","border-width":"1px","border-style":"solid"})

    anchor.read();
	
	$(".left_submenu>ul>li>a").each(function (){
		var a_tab = $("<a class='red_tri'>&nbsp;</a>");
		a_tab.attr("href", $(this).attr("href"));
		$(this).after(a_tab);
	});
    $(".left_submenu li a").click(function (e) {
        e.stopPropagation();
    });

    $(".left_submenu li").click(function (e) {
        //	document.location=$(this).find("a").attr("href");
        e.stopPropagation();
        var a = $(this).addClass("clicked").find("a");
        if ((a.attr("target") == "_self") || (!a.attr("target"))) {
            a.click();
        } else {
            window.open(a.attr("href"));
        }
    });


    /* PreLoad image */
    $.preLoadImages(xpath.img + "/loader1.gif");
    /* Smooth scroll for "Back To Top" */
    $('p.backToTop a').bind('click', function (e) {
        if (e.button != 0) return;
        var target = ($($(this).attr('href')).length > 0) ? $($(this).attr('href')) : $($(this).attr('anchor'))
        $.scrollTo(target);
    });


    if ($(".index_banner, .right_column").length == 0) $(".main_container").addClass("no_rightpanel");

    //init navigation and tools	
    topmenu.init();
    leftmenu();
    init_top_tools();
    mygoogle.topbar.init();

    //restore function from cookie setting 
    sizeselector.init();
    contrast.init();

    //index page
    init_index_page_items();

    //init often used modules, if they exists
    afterload("body");


    $(".index_news>ul>li>a").click(function () {
        $(this).parents("li:eq(0)").addClass("active").siblings("li").removeClass("active");
        var index = $(this).parents("li").index();
        $('#index_container .index_news div.index_right_tab').hide();
        $('#index_container .index_news div.index_right_tab').eq(index).show();
        if ($('div.index_right_tab').length > 0) {
            $('div.index_right_tab').jScrollPane({ "showArrows": true, "verticalDragMinHeight": 23, "verticalDragMaxHeight": 23 });
        }
    });
    $(".index_news>ul>li>a:eq(0)").click();

    //adbox.init();

    // SHKPXtra
    $(".left_submenu li a").each(function () {
        if ($(this).length > 0)
            $(this).html($(this).html().toString().replace("Xtra", "<em>Xtra</em>"));
    });

    //mygoogle.check();

    initHashChange();

    if ($("#tung-shing-calendar").length > 0) {
				 $.ajax({
   			url: "/Content/xml/tungshing/setup-value.txt",
   			dataType: 'text',
   			success: function(data){
				 var datas = []
				 var tempDatas = data.split('&');
				 for(var i in tempDatas){
					 var tempData = tempDatas[i].split('=');
					 console.log(tempData[0]);
					 datas[tempData[0]] = tempData[1]
				 }
        ts = new TungShung({ "body": $("#tung-shing-calendar"), "days": days.split(","), "months": months, "icons": icons,  "startDate":datas['start'], "endDate":datas['end'], "lunar": true,
            "dateMessage": "通 勝 目 前 只 提 供 2011 年 1  月 1 日 至 2012 年 1 月 22 日 的 事 項， 其 後 的 資 料 將 於 稍 後 上 網。"
        });
        ts.init()
						}
			})
    }

    propertyDropDown.init();

    $('#customizeFeedback').submit(function () {
        //e.preventDefault();
        var failField = $('#customizeFeedback .check').validation();
        if (failField.length > 0) {
            var warningMsg = '';
            failField.each(function () {
                var dummy = $(this);
                warningMsg += $('#warningMsg .fail' + dummy.attr('class').split('fail')[1].split(' ')[0] + '.' + dummy.attr('id')).text() + '\n';
            });
            alert(warningMsg);
            return false;
        }
    });
});
$(window).load(function(){
	flash_typeSelected('1');
})

var days = "日,一,二,三,四,五,六";
var months = new Array("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月")
var icons = new Array()
icons[icons.length] = {"id":"1","label":"求婚","img":"1.jpg"}
icons[icons.length] = {"id":"2","label":"訂婚","img":"2.jpg"}
icons[icons.length] = {"id":"3","label":"嫁娶","img":"3.jpg"}
icons[icons.length] = {"id":"4","label":"置業","img":"4.jpg"}
icons[icons.length] = {"id":"5","label":"遷移","img":"5.jpg"}
icons[icons.length] = {"id":"10","label":"新居入伙","img":"10.jpg"}
icons[icons.length] = {"id":"6","label":"安床","img":"6.jpg"}
icons[icons.length] = {"id":"7","label":"裝修房屋","img":"7.jpg"}
icons[icons.length] = {"id":"22","label":"動土","img":"22.jpg"}
icons[icons.length] = {"id":"8","label":"剪髮","img":"8.jpg"}
icons[icons.length] = {"id":"9","label":"拜師入學","img":"9.jpg"}
icons[icons.length] = {"id":"11","label":"會友","img":"11.jpg"}
icons[icons.length] = {"id":"13","label":"大掃除","img":"13.jpg"}
icons[icons.length] = {"id":"14","label":"旅行公幹","img":"14.jpg"}
icons[icons.length] = {"id":"24","label":"收養寵物","img":"24.jpg"}
icons[icons.length] = {"id":"18","label":"開市","img":"18.jpg"}
icons[icons.length] = {"id":"12","label":"新職到任","img":"12.jpg"}
icons[icons.length] = {"id":"20","label":"進貨、收賬","img":"20.jpg"}
icons[icons.length] = {"id":"19","label":"簽約","img":"19.jpg"}
icons[icons.length] = {"id":"15","label":"祭祀、祈福","img":"15.jpg"}
icons[icons.length] = {"id":"16","label":"喪事","img":"16.jpg"}
icons[icons.length] = {"id":"17","label":"安葬","img":"17.jpg"} 
//icons[icons.length] = {"id":"21","label":"銷貨放債","img":"21.jpg"}
//icons[icons.length] = {"id":"23","label":"種風水樹","img":"23.jpg"}
icons[icons.length] = {"id":"25","label":"是日無特別注意事項","img":"25.jpg"}
icons[icons.length] = {"id":"26","label":"沒有[gd][item]的日子","img":"25.jpg"}

for(i in icons){
	icons[i].img = "/Content/Images/tungshing/icon/"+icons[i].img;
}

var jsArray = ['/Content/Scripts/tung_shing.js', '/Content/Scripts/jquery.mousewheel.js', '/Content/Scripts/jquery.jscrollpane.min.js'];

for(var i=0;i<jsArray.length;i++){
	document.write('<script type="text/javascript" src="'+jsArray[i]+'" ></scr'+'ipt>'); 
}

/* ============================================================================================================*/
/* ==========================================procedural functions =============================================*/
/* ============================================================================================================*/


var afterload = function () {
    //	$("a[href$=#]").attr("href","javascript:void(0)");
    var scope = (arguments.length > 0) ? arguments[0] : $("#mainContent2").length ? "#mainContent2" : "#mainContent";
    console.group("After Load: %o", $(scope));
    $("a[href^=" + anchor.urlPrefix + "]").each(function () {
        $(this).attr("href", $(this).attr("href").toString().replace(anchor.urlPrefix, ""));
    });
    try {
        $("a").not("[href^=\"/" + currentCulture + "\"]").each(function () {
            var me = $(this);
            if (me.attr("href")) {

                if (me.attr("href").toString().indexOf("#") === 0) {
                    if ((me.attr("href").toString().indexOf("#/") !== 0) && (me.attr("href").toString().indexOf("#" + anchor.urlPrefix) !== 0)) {
                        if (me.attr("href").toString() != "#") {
                            me.attr("anchor", me.attr("href"));
                        }
                        if (me.parents(".tabs").length == 0) me.attr("href", "javascript:void(0)");
                    }
                }

                var isexcluded = false;
                var excludeList = ["#", "#/", "#" + anchor.urlPrefix, "javascript", "http", "ftp", "/e-news/", "/html/", "/content/", "mailto", "tel:", "/en-us/", "/zh-hk/", "/zh-cn/"];
                for (var exclude in excludeList) {
                    isexcluded = isexcluded || (me.attr("href").toString().toLowerCase().indexOf(excludeList[exclude]) === 0);
                }
                if (!isexcluded) {
                    me.attr("href", "/" + currentCulture + me.attr("href"));
                }

            }
        });
    } catch (e) { }
    submenu();
    init_tabs(scope);
    init_photo_slideshow();
    video_carousel.init();
    director.init();
    investor.init();
    stock.init();
    properties.init();
    relatedLinks();
    $("a.btn_enlarge").colorbox({ width: "75%" });
    $("a.colorBox").colorbox({ height: "75%" });
    searchBox.build();
    setHint();
    $("a.links").each(function () {
        if ($(this).parents("div.linkswrapper").length == 0) {
            $(this).wrap('<div class="linkswrapper">');
        }
    });
    $("input.btn_reset").click(function () {
        $(this).parents("form").find("input, textarea").not("input[type=radio]").removeClass("input-validation-error").val("");
        $(".field-validation-error").hide();
        return false;
    });
    if ($('.awardfilter').html() == '2099') {
        $('.awardfilter').html('最新獎項');
		
	}
	var latest = false;
	$('#yearFilter option').each(function(){
		if($(this).html()=="2099"){
			$(this).html('最新獎項');
			latest = true;
		}
		if($(this).html()=="2098/2099"){
			$(this).html('最新');
		}
	});
	if(latest){
		if($('#yearFilter option:first').html()=="年份"){
			$('#yearFilter option:first').remove();
		}
	}
    console.groupEnd();
}

var relatedLinks=function(){
	var right=$(".right_column .relatedLinks");
	var main=$("#mainContent ul.subRelatedLinks");
	
	if (main.find("li").length>0){
		right.find("ul").html(right.find("ul").html()+main.html());
		right.show();
	}else{
		if (right.find("ul li").length>0){
			right.show();
		}else{
			right.hide();
		}
	}
}


/* google search */
var mygoogle={
	resultTimer:null,
	page:"/Pages/quick-links-search",
	topbar:{
		init:function(){
		    if ($('#searchresult').length > 0) {
		        $('#searchresult').hide();
		    }
            if (typeof (anchor.parameter["googlesearch"]) != "undefined") {
				$(".search-box input[name=q]").attr("value", unescape(anchor.parameter["googlesearch"]));
				mygoogle.searchpage.search($(".search-box input[name=q]").attr("value"));
			}
			$(".search-box input[name=q]").bind("keyup", function(e){
				if (e.keyCode == 13) {
					mygoogle.topbar.search($(this).attr("value"));
					return(false);
				}
			});	
			$(".search-box input[name=sa]").bind("click", function(e){
				if (!$(".search-box input[name=q]").hasClass("hint_Showing")){
					mygoogle.topbar.search($(".search-box input[name=q]").attr("value"));
				}
				return(false);
			});
			$('.search-box input[name=sa]').keyup(function(e) {
				if(e.keyCode == 13) {
					if (!$(".search-box input[name=q]").hasClass("hint_Showing")){
						mygoogle.topbar.search($(".search-box input[name=q]").attr("value"));
					}
				}
				return(false);
			});
            $("form[name=cse]").submit(function () {
                return (false);
            });
		},
		search:function(text){
			var loc=window.location.toString();
			if (loc.indexOf(mygoogle.page)>-1){
				mygoogle.searchpage.search(text);
			}else{
				document.location=mygoogle.page+"#googlesearch="+escape(text);
			}
		}
	},
	searchpage:{
		search:function(text){
			$("#tester_txt").attr("value", text);
			if ($("#searchcontrol input.gsc-input").length>0){
				$("#tester_send").click();
			}else{
                setTimeout(function () { mygoogle.topbar.search(text) }, 250);
                setTimeout(function () { mygoogle.check() }, 2000);
			}
		}
	},
	check:function(){
		var result=$(".gsc-webResult.gsc-result");
		if(result.length==0){
			$("#searchresult [title=found]").hide();
			$("#searchresult").show();
		}else{
			$("#searchresult").hide();
		}
		clearTimeout(mygoogle.resultTimer);
		mygoogle.resultTimer=setTimeout(mygoogle.check,1000);
	}
}


/* Top Menu */
var topmenu = {
    focusClass: null,
    menuClass: ".main_menu",
    init: function () {
        var me = $(topmenu.menuClass).children("li");
        me.hover(
            function () {
                topmenu.enter($(this));
            },
            function () {
                topmenu.leave($(this));
            }
        );
        me.children("a").focus(function () {
            var obj = $(this).parents(topmenu.menuClass + ">li");
            if (topmenu.focusClass != null) topmenu.leave($("." + topmenu.focusClass));
            topmenu.focusClass = obj.attr("class").split(' ')[0];
            topmenu.enter(obj);
        });
        me.find("a").focusout(function () {
            var obj = $(this).parents(topmenu.menuClass + ">li");
            if (obj.attr("class").split(' ')[0] != topmenu.focusClass) {
                topmenu.leave(obj);
            }
        });
        $("a").focus(function () {
            var obj = $(this).parents(topmenu.menuClass + ">li");
            if (obj.length == 0 && topmenu.focusClass != null) {
                topmenu.leave($("." + topmenu.focusClass));
                topmenu.focusClass = null;
            }
        });
    },
    enter: function (me) {
        me.addClass('selected').siblings().removeClass('selected');
        if (me.css('background-position-y')) {
            me.css('background-position-y', '-27px');
        } else {
            me.css('background-position', me.css('background-position').split(' ')[0] + " -27px");
        };
		// Create a dynamic iframe to cover the form select input for IE6.
		me.children("div").css("z-index", 100);
		if (($.browser.msie)&&(parseInt($.browser.version)==6)){
			if (!me.children().hasClass("hiddenframe")) {
				$("<iframe />", {
					"class" : "hiddenframe",
					"frameborder" : 0,
					width : me.children("div").innerWidth(),
					height : me.children("div").innerHeight()
				}).css({
					"z-index": 50,
					"position": "absolute",
					"top": me.children("div").css("top"),
					"left": me.children("div").css("left")
				}).appendTo(me);
			}
			else {
				me.children(".hiddenframe").show();
			}
		}
    },
    leave: function (me) {
        me.removeClass("selected");
        if (me.css('background-position-y')) {
            me.css('background-position-y', '0px');
        } else {
            me.css('background-position', me.css('background-position').split(' ')[0] + " 0px");
        };
		// Remove the dynamic iframe for IE6
		me.children("div").css("z-index", null);
		me.find("iframe.hiddenframe").hide();
    }
}

function submenu(){
	$('.sub_menu>li').unbind("mouseover").mouseover(function(){
		$(this).addClass("active").siblings().removeClass("active");
		var html=$.trim($(this).find("div").html());
		$("div.sharepanel").html(html).show();
		$("div.sharepanel .tabinited").removeClass("tabinited");
		init_tabs("div.sharepanel");
	});
	$('div.sub_menu').hover(
		function () {
		  	var html=$.trim($('.sub_menu>li.active div').html());
			if (html!==""){
				$("div.sharepanel").html(html).show();
				$("div.sharepanel .tabinited").removeClass("tabinited");
				init_tabs("div.sharepanel");				
			}
	    }, 
	    function () {
			$("div.sharepanel").hide();
			$('.sub_menu>li').removeClass("active");
	    }	
	)
};


function leftmenu(){
		/* left menu for set "current" */
	parent_menu=$('.left_submenu ul .current').parent('ul').parent('li');
	$('.left_submenu>ul>li.current>a').css('color','#ed1c24');
	$('.left_submenu ul .current').parent('ul').show();
	$('.left_submenu ul li.withmenu.current').css('background','url('+xpath.img+'/left_submenu_over.gif) no-repeat 98% 0.5em');
	$('.left_submenu ul .current ul').show();
	if(parent_menu.length>0){
			parent_menu.css('background','url('+xpath.img+'/left_submenu_over.gif) no-repeat 98% 0.5em');
			parent_menu.find('a:first').css('color','#ed1c24');
	}
//  the "first"	class is long-forgotten orphan?
//	$('.content p:first').addClass("first"); 
}


var searchBox={
	build:function(){

		var box=$(".rightseachbox");
		
		var date=new Date();
		box.find("select.year").each(function(){
											  $(this).empty();
		for (var i=date.getFullYear();i>=2006;i--){$("<option>").attr("value",i).html(i).appendTo($(this))}
											  });
		box.find("select.month").each(function(){
											  $(this).empty();
		for (var i=1;i<=12;i++){$("<option>").attr("value",i).html(smonthName[i-1]).appendTo($(this))}
											  });
		
		box.find("select[name=year], select[name=to_year]").attr('value', date.getFullYear()+"");
		box.find("select[name=from_year]").attr('value', date.getFullYear()+"");
		box.find("select.month").attr('value', (date.getMonth()+1)+"");
/*		box.find("select[name=year], select[name=to_year]").find("option[value="+date.getFullYear()+"]").attr("selected","selected");
		box.find("select[name=from_year]").find("option[value="+(date.getFullYear()-1)+"]").attr("selected","selected");
		box.find("select.month").find("option[value="+(date.getMonth()+1)+"]").attr("selected","selected");*/
		
		box.find(".search").click(function(){
			box.find("input.hint_Showing").attr("value","");
			box.find("form").submit();
		})
		
		box.find('select[name="from_month"], select[name="from_year"], select[name="to_month"], select[name="to_year"]').change(function (){
			box.find('input[value="range"]').attr('checked', true);
		});
		
		box.find('select[name="year"]').change(function (){
			box.find('input[value="singleyear"]').attr('checked', true);
		});
		
	}
}


/* Index Banner */
function index_banner(){
	$('#index_container .index_banner').cycle({
		fx:     'fade',
		timeout: 5000,
		speed:  2000,
		pager:  '#nav',
		slideExpr: '#slideshow img'
	});
};



/* Box Expend */

var investor={
    init: function () {
        // prevent firefox 5 double load.
        var loaded = false;
        var firstImage = $("div.box2.investor .box2-content:eq(0)>ul:eq(0)>li>img");
        // Add random to override the image cache skipped load event
        var firstImageSrc = firstImage.attr('src');
        $("div.box2.investor .box2-header").click(investor.display);
        firstImage.load(function () {
            // check if not loaded then click the image box once to expand.
            if (!loaded) {
                $("div.box2.investor .box2-header:eq(0)").click();
                loaded = true;
            }
            console.log("Investor First Image " + firstImage.attr('src') + " loaded");
        }).attr('src', firstImageSrc);
    },
    display: function () {
	    var me = $(this);
	    var siblings = me.parents(".investor:eq(0)").siblings(".investor");
	    siblings.find('.box2-content').slideUp('middle');
	    siblings.find('.box2-header h2').removeClass('current');
	    if (me.find("h2").hasClass("current")) {
	        me.siblings('.box2-content').slideUp('middle');
	        me.find('h2').removeClass('current');
	    } else {
	        var h = me.siblings('.box2-content').height();
	        me.siblings('.box2-content').css("height", "0px").animate({
	            "height": h + "px"
	        }, "middle", function () {
	            var me2 = $(this);
	            me2.children().find('ul').show(function () {
	                me2.css("height", "auto");
	                me2.css("width", "536px");
	            });
	            /*
	            me2.parent('.investor').children().find('ul').show(function (){
	            me2.css("height", "auto");
	            });
	            */
	        });

	        //			me.siblings('.box2-content').slideDown('middle');
	        //me.siblings('.box2-content').show('middle');
	        me.find('h2').addClass('current');
	    }
	}
}
/*
function bind_box(){
	bind_obj.unbind('click.show');
	bind_obj.bind('click.show',function(){
		display_box($(this));
	});
}
function display_box(obj){
	bind_obj.unbind('click.show');
	click_tab=obj.parent('div.box2').index()-2;
	current_status=(current!=null)?$('div.box2:eq('+current+') .box2-header h2').hasClass('current'):false;
	click_status=obj.find('h2').hasClass('current');
	if(current_status){
		$('div.box2:eq('+current+') .box2-header h2').removeClass('current');
		$('div.box2:eq('+current+') .box2-content').slideUp('middle',function(){bind_box()});
	}
	if(!click_status){
		$('div.box2:eq('+click_tab+') .box2-header h2').addClass('current');
		$('div.box2:eq('+click_tab+') .box2-content').slideDown('middle',function(){bind_box()});
	}
	current=click_tab;
}
*/



/*Photos*/
function photo_slideshow(){
	$(".slideshow .nav").empty();
	
	$('#photos .slideshow').cycle({
		fx:     'scrollLeft',
		timeout: 4000,
		speed:  800,
		pager:  '.slideshow .nav',
		slideExpr: '.photo',
		before: function(curr, next, opts){
			var index = opts.nextSlide;
			$('#photos .custom-nav a:eq('+index+')').addClass('activeSlide').siblings().removeClass('activeSlide');
/*			var me=$('#photos .slideshow div:eq('+index+')');
			me.parents(".slideshow").animate({"height":me.height()+"px"}, "fast");*/
		}
	});
	$('#photos .caption').cycle({
		fx:     'none',
		timeout: 4000,
		pager:  '.caption .nav',
		slideExpr: 'p'
	});
}

/* Video */
function show_video(video,width,height,auto,mute){
	var Vars = {};
	Vars.allowfullscreen = "true";	
	Vars.allowscriptaccess = "always";
	Vars.wmode = "opaque";
	//Vars.wmode = "transparent";
	if (typeof(video)=="string"){
		Vars.file = xpath.flv+"/"+video+'.flv';
		Vars.image = xpath.flv+"/"+video+'.jpg';
	}else{
		Vars.file = video.videoname;
		Vars.image = video.jpgname;
	}
    Vars.stretching = "uniform";
	Vars.autostart = auto;
	/*Vars.dock = "false";*/
	Vars.mute = mute;
	/*Vars.icons = "false";*/
	Vars.allowfullscreen = "true";
	if (video.xmlname != null) {
	    var captionfile = video.xmlname;
	    Vars.plugins = "captions-2h&captions.back=true&captions.file=" + captionfile + "&captions.pluginmode=FLASH&controlbar.position=over";
	}
	var Params = { wmode: "transparent", allowfullscreen: "true"};
	var Attributes = {};
	swfobject.embedSWF(xpath.loader+'/player.swf','media_container',width,height,'9',xpath.loader+"/expressInstall.swf", Vars, Params, Attributes);
	/*try{
		$("#media_container").attr({
			name:"player",
			classid:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
		}).removeAttr("data");
		$('<param value="/Content/Scripts/player.swf" name="movie">').appendTo($("#media_container"));
		$('<embed height="'+height+'" width="'+width+'" flashvars="file='+Vars.file+'&amp;image='+Vars.image+'" allowfullscreen="true" allowscriptaccess="always" src="/Content/Scripts/player.swf" name="player2" id="player2" type="application/x-shockwave-flash">').appendTo($("#media_container"));
	}catch(e){} */
}

function init_top_tools(){
	/*
	$(".top_tools .tools-share").html('<div id="social_button"><img src="'+xpath.img+'/socialutilities_fb.gif" alt="Facebook"/><img src="'+xpath.img+'/socialutilities_twitter.gif" alt="Twitter"/><img src="'+xpath.img+'/socialutilities_email.gif" alt="Email"/></div><div id="social_bubble"><img src="'+xpath.img+'/socialutilities_tail.gif" alt=""/></div>'+$(".top_tools .tools-share").html()).hover(
		function(){$(".top_tools .tools-share div").show();},
		function(){$(".top_tools .tools-share div").hide();}
	);*/
	$(".top_tools .tools-share").html('<div id="social_box"><img src="'+xpath.img+'/socialutilities_header.gif" alt="" class="head"/><div><img src="'+xpath.img+'/facebook_icon.gif" alt="Facebook"/><img src="'+xpath.img+'/titter_icon.gif" alt="Twitter"/><img src="'+xpath.img+'/weibo_icon.gif" alt="Weibo"/><img src="'+xpath.img+'/friends_icon.gif" alt="Email"/></div></div>'+$(".top_tools .tools-share").html()).hover(
		function(){$(".top_tools .tools-share #social_box").show();},
		function(){$(".top_tools .tools-share #social_box").hide();}
	);
	$(".top_tools .tools-share [alt=Facebook]").css({"cursor":"pointer"}).click(function(){
		_gaq.push(['_trackEvent', 'Share', 'Facebook', 'Share To Facebook']);
//		winopen.open("http://www.facebook.com/share.php?u="+escape(document.location.toString()));
		window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(document.location.toString()), 'sharer', 'toolbar=0,status=0,width=626,height=436');
	});
	$(".top_tools .tools-share [alt=Twitter]").css({"cursor":"pointer"}).click(function(){
		_gaq.push(['_trackEvent', 'Share', 'Twitter', 'Share To Twitter']);
//		winopen.open("http://twitter.com/share?url="+escape(document.location.toString())+"&text=" + document.title+escape("\n"));
		window.open('http://twitter.com/share?url=' + escape(document.location.toString()) + "&text=" + document.title + escape("\n"), 'sharer','toolbar=0,status=0,width=800,height=436');
	});
	$(".top_tools .tools-share [alt=Weibo]").css({"cursor":"pointer"}).click(function(){
		_gaq.push(['_trackEvent', 'Share', 'Weibo', 'Share To Weibo']);
//		winopen.open("http://v.t.sina.com.cn/share/share.php?title="+escape(document.location.toString())+"+"+document.title);
		window.open("http://v.t.sina.com.cn/share/share.php?title=" + escape(document.location.toString()) + "+" + document.title, 'sharer', 'toolbar=0,status=0,width=620,height=330');
	});
	$(".top_tools .tools-share [alt=Email]").css({"cursor":"pointer"}).click(function(){spotlight.init(xpath.spotlight+"/forwardemail.html")});

//	$(".top_tools .tools-reply").click(function(){spotlight.init(xpath.spotlight+"/reply.html")});
	$(".top_tools .tools-bookmark").click(bookmark.init);
	
	$(".top_tools .tools-contrast").click(function(){contrast.darken();});
	$(".top_tools .tools-fontsize-increase a").click(sizeselector.sizeup);
	$(".top_tools .tools-fontsize-decrease a").click(sizeselector.sizedown);
	$(".top_tools .tools-print").click(function(){window.print();});
	
}


function init_index_page_items(){
	index_banner();
	$('div.index_csr .carousel').jcarousel({
		auto: 10,
		scroll: 1,
		wrap: 'circular',
		initCallback: function (carousel) {
			$('div.index_csr .carousel li').css({
				"position": "static",
				"visibility": "visible"
			});
			$('div.index_csr .scrollingRight').bind('click', function () {
				carousel.next();
				mycarousel_buttonNextCallback();
				return false;
			});
			$('div.index_csr .scrollingLeft').bind('click', function () {
				carousel.prev();
				mycarousel_buttonPrevCallback();
				return false;
			});
		}
	});
//	if ($(".index_video").length>0) show_video('SHKP_corpvideo_2010_c', '240', '170', 'true', 'true');
	properities_box.init();
}

function init_photo_slideshow(){
	if($('#photos').length>0){
		/*Photos*/
		$('#photos .caption, #photos .photo').show();
		photo_slideshow();
		$('#photos .custom-nav').empty();
		$('#photos .custom-nav').html($('#photos .slideshow .nav').html());
		$('#photos .custom-nav a').click(function() { 
			num = $(this).index();
			$('#photos .slideshow a:eq('+num+')').trigger('click');
			$('#photos .caption a:eq('+num+')').trigger('click');
			$(this).addClass('activeSlide').siblings().removeClass('activeSlide');
			return false; 
		});
	}
	
    $('#photos img').load(function(){
		var parent = $(this).parents('.slideshow');
		if($(this).attr('height') > parseInt(parent.css('height'))){
			parent.css({"height":($(this).attr('height') + 20) +"px"});
		}
	});
}


/* ============================================================================================================*/
/* =========================================== module functions ===============================================*/
/* ============================================================================================================*/

// ===== spotlight, by lith ==============
/*
var spotlight={
	
	init:function(src){
		var bg=$("#dimbackground");
		if (bg.length==0){
			bg=$("<div>").attr({"id":"dimbackground"}).css({
				"left":"0px",
				"top":"0px",
				"width":$("body").width()+"px",
				"height":$("body").height()+"px"
			}).appendTo($("body"));
		}
		$("html").addClass("dimmed");
		bg.fadeTo('fast', 0.64, function(){$("#dimbackground").unbind('click');$("#dimbackground").click(spotlight.close)});

		var fg=$("#dimforeground");
		if (fg.length==0){
			fg=$("<div>").attr({"id":"dimforeground"}).appendTo($("body"));
		}
		if (typeof(src)=="string"){
			fg.load(src, this.loaded);
		}else{
			src.appendTo(fg.empty());
			this.loaded.call();
		}
		
	},
	
	loaded:function(){
		var fg=$("#dimforeground");
		
		fg.find("[src]").each(function(){
			$(this).attr("src", $(this).attr("src"));
		});
		
		fg.find(".close").click(spotlight.close);
		spotlight.center(false);
		setHint();
	},
	
	center:function(animate){
		var fg=$("#dimforeground");
		var data={
			"left":(($(window).width()-fg.width())/2)+"px",
			"top":(($(window).height()-fg.height())/2)+"px"
		}
		if (animate){
			fg.animate(data, 'fast');
		}else{
			fg.css(data);
		}
	},
	
	close:function(){
		$("#dimbackground").fadeTo('fast', 0, function(){$("html").removeClass("dimmed");});
	}
}
*/

var spotlight={
	
	init:function(src){
		
		$('body').addClass('spotlight');
		
		if (typeof(src)=="string"){

			$.colorbox({
				href: src, 
				arrowKey: false,
				onComplete:function (){
					$('#cboxWrapper .close').click(spotlight.close);
					$.colorbox.resize();
					$.colorbox.resize();
				}, 
				onClosed: function (){
					$('body').removeClass('spotlight');	
				}
			});
				
/*			$.fancybox({
				href: src, 
				type: 'ajax',
				showCloseButton: false, 
				padding: 0, 
				overlayColor: '#000', 
				overlayOpacity: 0.64, 
				autoDimensions: true,
				onComplete: function(){
					$('#fancybox-content .close').click(spotlight.close);
			}});*/
		}else{
			$.colorbox({
				html: src, 
				arrowKey: false,
				onComplete:function (){
					$('#cboxWrapper .close').click(spotlight.close);
					$.colorbox.resize();
					$.colorbox.resize();
				}, 
				onClosed: function (){
					$('body').removeClass('spotlight');	
				}
			});
		}
		
	},
	
	close:function(){
//		$.fancybox.close();
		$.colorbox.close();
	}
}





// ===== adbox, by lith ==============
// ===== connects to api/adbox_data.js for data

var adbox={
	init:function(){
		if ($(".right_column").length>0){
			//==== for temp
			$(".right_column a.adbox").empty().remove();

			
//			$.getJSON(xpath.adbox+"/adbox_data.js", this.loaded);


			$.ajax({ 
				url:xpath.adbox+"/adbox_data.xml", 
				type: 'get', 
				datatype: ($.browser.msie) ? "text" : "xml",
				error: function(xml){ 
					  alert('error loading xml document'+xml); 
				}, 
				success: this.loaded
				
			}); 

			
		}
	},
	
	loaded:function(strXML){
		var xml;
		try {
			xml = new ActiveXObject("Microsoft.XMLDOM");
			xml.async = false;
			xml.loadXML(strXML);
		} catch(e){
			xml = strXML;
		}	

		var boxes=$(xml).find("imagebox");

		var pointer=$(".right_column .relatedLinks");
		for (var i=0;i<boxes.length;i++){
			var rand=Math.floor(Math.random()*$(boxes[i]).children().length);
			var me=$(boxes[i]).children("option:eq("+rand+")");
			var a={
				"href":me.children("href").text(),
				"alt":me.children("alt").text()
			}
			var img={
				"src":xpath.adbox+"/"+me.children("src").text(),
				"alt":me.children("alt").text()
			}
			try{
				a["target"]=me.children("target").text();
			}catch(e){
			}
			var a=$("<a>").attr(a).addClass("adbox").insertBefore(pointer);
			$("<img>").attr(img).appendTo(a);
		}

		
	}
}


var textlink={
	render:function(json){
		var ul=$(".right_column ul").empty();
		
		for (var i=0;i<json.text_link.length;i++){
			$("<a>").attr(json.text_link[i]).html(json.text_link[i].title).appendTo($("<li>").appendTo(ul));
		}
	}
}



	
	
/* check if popup is blocked  */
var winopen={
	timer:null,
	open:function(src){
		window.open('/Content/Scripts/winopener_checker.html#'+escape(src));
		this.timer=setTimeout(this.error, 2000);
	},
	markdone:function(){
		clearTimeout(this.timer);
	},
	error:function(){
		alert("Popup is blocked!");
		clearTimeout(this.timer);
	}
}


var bookmark={
	list:[],
	page:1,
	pagesize:9,
	paginsize:9,
	api_path:"/Bookmarks",
	init:function(){
		if (bookmark.getid()==""){
			spotlight.init(xpath.spotlight+"/bookmark_add.html");
		}else{
			spotlight.init(xpath.spotlight+"/bookmark.html");
		}
	},
	getid:function(){
		var temp=$.cookie("SHK_bookmark");
		return((temp!=null)?temp:"");
	},
	setid:function(tempkey){
		$.cookie("SHK_bookmark", tempkey, cookieSetting);
	},
	add:function(data){
		if (this.getid()!="") data["UniqueId"]=this.getid();
		$.post(this.api_path+"/Create/", data, function(text){
			if (text!="") bookmark.setid(text);
			spotlight.close();
		});
	},
	del:function(idx){
		var data={
			"Id":idx,
			"UniqueId":this.getid()
		}
		for (var i=0;i<this.list.length;i++){
			if (this.list[i]["Id"]==idx){
				this.list.splice(i,1);
				break;
			}
		}
		$.get(this.api_path+"/Delete/", data, function(){bookmark.del_animation(idx)});
	},
	del_animation:function(idx){
		var target=$("#bookmark_content .entries:not(.dummy) img[idx="+idx+"]").parents(".entry");
		target.animate({
			"opacity":0,
			"height":"0px"
		}, function(){target.remove();bookmark.resize();});
		
		$("#bookmark_content .entries:not(.dummy) .entry:visible:last").next(".entry").show();
		
	},
	load:function(){
		var data={};
//		spotlight.center(false);
		$.getJSON(bookmark.api_path+"/Index/"+bookmark.getid()+"?r="+Math.random(), data, function(result){
			bookmark.list=result;
			bookmark.render();
		});
	},
	render:function(){
		//render content
		
		var dummy=$("#bookmark_content .entries.dummy .entry");
		var target=$("#bookmark_content .entries:not(.dummy)").empty();
		for (var i=0;i<bookmark.list.length;i++){
			var new_me=dummy.clone().appendTo(target);
			new_me.find(".desc").html(bookmark.list[i]["Title"]);
			new_me.find(".url a").html(bookmark.list[i]["Url"]).attr("href",bookmark.list[i]["Url"]);
			new_me.find(".fright img").attr("idx",bookmark.list[i]["Id"]).click(function(){bookmark.del($(this).attr("idx"))});
			var ubound=bookmark.page*bookmark.pagesize;
			var lbound=(bookmark.page-1)*bookmark.pagesize;
			if((i<lbound)||(i>=ubound)){
				new_me.hide();
			}
		}
		
		$("#bookmark_content").removeClass("loading");
		
		bookmark.resize();
		
	},
	resize:function(){
		this.renew_pagination();
		$.colorbox.resize();
		$.colorbox.resize();
		
	},
	
	renew_pagination:function(){
		var pagin=$("#bookmark_content .pagination");
		if(this.list.length>this.pagesize){
			var maxpage=Math.ceil(this.list.length/this.pagesize);
			if (this.page>maxpage) this.page=maxpage;
			
			var lbound=this.page-Math.floor(this.paginsize/2);
			var ubound=this.page+Math.ceil(this.paginsize/2);
			if (lbound<1){ubound+=1-lbound;lbound=1;}
			if (ubound>maxpage){lbound-=ubound-maxpage;ubound=maxpage;}
			if (lbound<1){lbound=1;}
			
			pagin.empty();
//			if (this.page>1){
				$("<div>").addClass("fleft").attr("title","prev").html("&#x2039;").appendTo(pagin).click(function(){bookmark.page=Math.max(1, bookmark.page-1);bookmark.render()});
//			}
			for (var i=lbound;i<=ubound;i++){
				var div=$("<div>").addClass("fleft").attr("page",i).html(i).appendTo(pagin).click(function(){bookmark.page=$(this).attr("page");bookmark.render()});
				if (i==this.page) div.addClass("currentpage");
			}
//			if (this.page<maxpage){
				$("<div>").addClass("fleft").attr("title","prev").html("&#x203A;").appendTo(pagin).click(function(){bookmark.page=Math.min(maxpage, bookmark.page+1);bookmark.render()});
//			}
			pagin.show();
		}else{
			this.page=1;
			pagin.hide();
		}
	}
	
}



var wordcount=function(source, target, maxnum){
	source.bind("keyup keypress blur mouseup mouseout",function(){
		var me=$(this);
		var text=(me.attr("type")==null)?me.html():me.attr("value");
		text=text.substr(0,maxnum);
		target.html(maxnum-text.length);
		if(me.attr("type")==null){
			me.html=text;
		}else{
			me.attr("value",text);
		}
	});
}

var setHint=function(){
	$("label.hint").each(function(){
		var source=$(this).find("textarea, input[type=text]");
		var hint=$(this).find(".hinttext");
		source.focus(function(){
			hint.hide();
		});
		source.blur(function(){
			var text=(source.attr("type")==null)?source.html():source.attr("value");
			if (text=="")hint.show();
		});
		source.blur();
	});
	$("textarea.hint, input.hint[type=text]").each(function(){
//		console.log("hint");
		$(this).focus(function(){
			if ($(this).hasClass("hint_Showing")){
				$(this).attr("value", "").removeClass("hint_Showing");
			}
		});
		$(this).blur(function(){
//			console.log("hint > "+$(this).attr("value"));
			if (($(this).attr("value")=="")||($(this).attr("value")==$(this).attr("title"))){
				$(this).attr("value", $(this).attr("title")).addClass("hint_Showing");
			}
		});
		$(this).blur();
	});
}

var video_carousel={
	data:null,
	init:function(){
		if ($("#video_wrap .video_carousel").length>0){
			
			$.getJSON(xpath.videoData, this.render);
		}
	},
	render:function(json){
		video_carousel.data=json;
		var parent=$("#video_wrap .video_carousel").empty();
		for (var i=0;i<json.length;i++){
			if(json[i].lang.length > 0){
				var li=$("<li>").attr("itemidx",i).click(function(){
					video_carousel.change($(this).attr("itemidx"),0);
				}).appendTo(parent).css({
						"position":"static",
						"visibility":"visible"
					});
				$("<img>").attr({"src":json[i].tn, "alt":json[i].tntext}).appendTo(li);
				$("<br/>").appendTo(li);
				$("<span>").html(json[i].tntext).appendTo(li);
			}
		}
		
		parent.jcarousel({
			scroll: 3,
			initCallback: function(carousel) {	
				$('#video_wrap .scrollingRight').bind('click', function() {
					carousel.next();
					mycarousel_buttonNextCallback();
					return false;
				});
				
				$('#video_wrap .scrollingLeft').bind('click', function() {
					carousel.prev();
					mycarousel_buttonPrevCallback();
					return false;
				});
			}
		});
		
		video_carousel.change(0,0);
		parent.css('width', (json.length * 174) +'px');
	},
	change:function(itemidx, langidx){
		var ref=video_carousel.data[itemidx];
		var video={
			videoname:ref.lang[langidx].flvsrc,
			jpgname:ref.lang[langidx].tnsrc,
			xmlname: ref.lang[langidx].xmlsrc
		}
		show_video(video,ref.width,ref.height,'false','false');
		
		var totalheight=ref.height+parseInt($("#media_container").css("margin-top"))+parseInt($("#media_container").css("margin-bottom"));
		
		$(".content .media .resizer").animate({"height":totalheight+"px"}, 'fast');
		
		var parent=$(".content .media .language").empty();
		$(".content .media p.title").html(ref.lang[langidx].alttext);
		for(var i=0;i<ref.lang.length;i++){
			if(ref.lang[i].flvsrc != null){
				$("<li>").attr({"itemidx":itemidx, "langidx":i}).click(function(){
					var me=$(this);
					video_carousel.change(me.attr("itemidx"),me.attr("langidx"));
				}).html(ref.lang[i].linktext).appendTo(parent);
			}
		}
	}
}

var contrast={
	preUpdateRules:[],
	
	totallevel:2,
	thresold:204,
	
	colornames:{"aliceblue": "#F0F8FF", "antiquewhite": "#FAEBD7", "aqua": "#00FFFF", "aquamarine": "#7FFFD4", "azure": "#F0FFFF", "beige": "#F5F5DC", "bisque": "#FFE4C4", "black": "#000000", "blanchedalmond": "#FFEBCD", "blue": "#0000FF", "blueviolet": "#8A2BE2", "brown": "#A52A2A", "burlywood": "#DEB887", "cadetblue": "#5F9EA0", "chartreuse": "#7FFF00", "chocolate": "#D2691E", "coral": "#FF7F50", "cornflowerblue": "#6495ED", "cornsilk": "#FFF8DC", "crimson": "#DC143C", "cyan": "#00FFFF", "darkblue": "#00008B", "darkcyan": "#008B8B", "darkgoldenrod": "#B8860B", "darkgray": "#A9A9A9", "darkgreen": "#006400", "darkkhaki": "#BDB76B", "darkmagenta": "#8B008B", "darkolivegreen": "#556B2F", "darkorange": "#FF8C00", "darkorchid": "#9932CC", "darkred": "#8B0000", "darksalmon": "#E9967A", "darkseagreen": "#8FBC8F", "darkslateblue": "#483D8B", "darkslategray": "#2F4F4F", "darkturquoise": "#00CED1", "darkviolet": "#9400D3", "deeppink": "#FF1493", "deepskyblue": "#00BFFF", "dimgray": "#696969", "dodgerblue": "#1E90FF", "firebrick": "#B22222", "floralwhite": "#FFFAF0", "forestgreen": "#228B22", "fuchsia": "#FF00FF", "gainsboro": "#DCDCDC", "ghostwhite": "#F8F8FF", "gold": "#FFD700", "goldenrod": "#DAA520", "gray": "#808080", "green": "#008000", "greenyellow": "#ADFF2F", "honeydew": "#F0FFF0", "hotpink": "#FF69B4", "indianred": "#CD5C5C", "indigo": "#4B0082", "ivory": "#FFFFF0", "khaki": "#F0E68C", "lavender": "#E6E6FA", "lavenderblush": "#FFF0F5", "lawngreen": "#7CFC00", "lemonchiffon": "#FFFACD", "lightblue": "#ADD8E6", "lightcoral": "#F08080", "lightcyan": "#E0FFFF", "lightgoldenrodyellow": "#FAFAD2", "lightgrey": "#D3D3D3", "lightgreen": "#90EE90", "lightpink": "#FFB6C1", "lightsalmon": "#FFA07A", "lightseagreen": "#20B2AA", "lightskyblue": "#87CEFA", "lightslategray": "#778899", "lightsteelblue": "#B0C4DE", "lightyellow": "#FFFFE0", "lime": "#00FF00", "limegreen": "#32CD32", "linen": "#FAF0E6", "magenta": "#FF00FF", "maroon": "#800000", "mediumaquamarine": "#66CDAA", "mediumblue": "#0000CD", "mediumorchid": "#BA55D3", "mediumpurple": "#9370D8", "mediumseagreen": "#3CB371", "mediumslateblue": "#7B68EE", "mediumspringgreen": "#00FA9A", "mediumturquoise": "#48D1CC", "mediumvioletred": "#C71585", "midnightblue": "#191970", "mintcream": "#F5FFFA", "mistyrose": "#FFE4E1", "moccasin": "#FFE4B5", "navajowhite": "#FFDEAD", "navy": "#000080", "oldlace": "#FDF5E6", "olive": "#808000", "olivedrab": "#6B8E23", "orange": "#FFA500", "orangered": "#FF4500", "orchid": "#DA70D6", "palegoldenrod": "#EEE8AA", "palegreen": "#98FB98", "paleturquoise": "#AFEEEE", "palevioletred": "#D87093", "papayawhip": "#FFEFD5", "peachpuff": "#FFDAB9", "peru": "#CD853F", "pink": "#FFC0CB", "plum": "#DDA0DD", "powderblue": "#B0E0E6", "purple": "#800080", "red": "#FF0000", "rosybrown": "#BC8F8F", "royalblue": "#4169E1", "saddlebrown": "#8B4513", "salmon": "#FA8072", "sandybrown": "#F4A460", "seagreen": "#2E8B57", "seashell": "#FFF5EE", "sienna": "#A0522D", "silver": "#C0C0C0", "skyblue": "#87CEEB", "slateblue": "#6A5ACD", "slategray": "#708090", "snow": "#FFFAFA", "springgreen": "#00FF7F", "steelblue": "#4682B4", "tan": "#D2B48C", "teal": "#008080", "thistle": "#D8BFD8", "tomato": "#FF6347", "turquoise": "#40E0D0", "violet": "#EE82EE", "wheat": "#F5DEB3", "white": "#FFFFFF", "whitesmoke": "#F5F5F5", "yellow": "#FFFF00", "yellowgreen": "#9ACD32"},
	
	init:function(){
	//init
		try{
			var ss = document.styleSheets;
	
			for (var i=0; i<ss.length; i++) {
				var rules = ss[i].cssRules || ss[i].rules;
				var type=(ss[i].cssRules)?"cssRules":"rules";
				for (var j=0; j<rules.length; j++) {
					if (typeof(rules[j].style)!="undefined"){
						if (typeof(rules[j].style.color)!="undefined"){
							if (rules[j].style.color!=""){
								contrast.preUpdateRules.push({"type":type,"i":i,"j":j,"color":rules[j].style.color});
							}
						}
					}
				}
			}
	
			
	
			var temp=$.cookie("SHK_contrast");
			if (temp!=null){
				if (isNaN(temp)) temp=0;
				this.darken(parseInt(temp));
			}
		}catch(e){}
			
	}, 
	
	darken: function(){
		if (arguments.length>0){
			var level=arguments[0];
		}else{
			var level=(parseInt($.cookie("SHK_contrast"))+1)%contrast.totallevel;
			if (isNaN(level)) level=0;
			$.cookie("SHK_contrast", level, cookieSetting);
		}
		if (level==0){
			contrast.normal();
		}else{
			$("body").addClass("verydark");
			/*
			for(var c=0;c<contrast.preUpdateRules.length;c++){
				var tmp=contrast.preUpdateRules[c];
				
				var rgb=contrast.getrgb(tmp.color);
				var r=contrast.ajcolor(rgb.r, level);
				var g=contrast.ajcolor(rgb.g, level);
				var b=contrast.ajcolor(rgb.b, level);
				
				document.styleSheets[tmp.i][tmp.type][tmp.j].style.color="rgb("+r+","+g+","+b+")";
			}
			*/
		}
	},
	
	normal:function(){
		$("body").removeClass("verydark");
		/*
		for(var c=0;c<contrast.preUpdateRules.length;c++){
			var tmp=contrast.preUpdateRules[c];
			document.styleSheets[tmp.i][tmp.type][tmp.j].style.color=tmp.color;
		}
		*/
	},
	
	ajcolor:function(value, level){
		value=parseInt(value);
		if (value>=this.thresold){
			//tune up
			return(parseInt(255-(255-value)*(this.totallevel-level)/this.totallevel));
		}else{
			//tune down
			return(parseInt(value*(this.totallevel-level)/this.totallevel));
		}
	},
	
	getrgb:function(code){
		if (typeof(this.colornames[code.toLowerCase()])!="undefined"){
			code=this.colornames[code.toLowerCase()];
		}
		if (code.charAt(0)=="#"){
			var rgb={
				"r":parseInt(code.substr(1,2),16),
				"g":parseInt(code.substr(3,2),16),
				"b":parseInt(code.substr(5,2),16)
			}
		}else{
			var tmp=code.split("(");
			var tmp=tmp[1].split(", ");
			var rgb={
				"r":parseInt(tmp[0], 10),
				"g":parseInt(tmp[1], 10),
				"b":parseInt(tmp[2], 10)
			}
		}
		
		return(rgb);
		
	}

}


var sizeselector = {
    minsize: 1,
    maxsize: 3,
    init: function () {
        this.fixedSize();
        var temp = $.cookie("SHK_fontsize");
        if (temp == null) {
            $.cookie("SHK_fontsize", 1, cookieSetting);
            temp = 1;
        } else {
            temp = parseInt(temp);
        }
        if (temp != 1) {
            this.sizeTo(temp);
        }
    },
    sizeTo: function (level) {
        var mybody = $("body");
        if (level >= sizeselector.minsize && level <= sizeselector.maxsize) {
            mybody.removeClass("fontsize_" + $.cookie("SHK_fontsize"))
            mybody.addClass("fontsize_" + level);
        }
        $.cookie("SHK_fontsize", level, cookieSetting);
        if ($('div.index_right_tab').length > 0) {
            $('div.index_right_tab').jScrollPane({ "showArrows": true, "verticalDragMinHeight": 23, "verticalDragMaxHeight": 23 });
        }

    },
    sizeup: function () {
        var level = parseInt($.cookie("SHK_fontsize"));
        if (level + 1 <= sizeselector.maxsize) {
            sizeselector.sizeTo(level + 1);
        }
    },
    sizedown: function () {
        var level = parseInt($.cookie("SHK_fontsize"));
        if (level - 1 >= sizeselector.minsize) {
            sizeselector.sizeTo(level - 1);
        }
    },
    /*  Exclude the class 'fixedFontSize'
        Initialize the min-fontsize before add the fontsize class to body
    */
    fixedSize: function () {
        // Create a temporary div to retrieve the minimum font-size
        $("body").append("<div id='tempDiv' style='display:none'></div>").addClass("fontsize_" + sizeselector.minsize);
        var minFontSize = $("#tempDiv").css("font-size");
        $("#tempDiv").remove();
        // Apply the min fontsize to the element which not applicate to dynamic fontsize
        $(".fixedFontSize").each(function () {
            $(this).css("font-size", minFontSize);
        });
    }
}



var properities_box={
	current:1,
	init:function(){
		properities_box.show(properities_box.current);
		$('.index_properties .tab li').click(function () {
			var index = $(this).index() + 1;
			if (properities_box.current != index) {
				$(this).addClass('current').siblings().removeClass('current');
				properities_box.show(index);
			}
			return false;
		});
		//$('.index_properties .tab').after('<div style="height: 187px; width: 475px;" class="loader"><img class="loader1" src="' + path + '/Images/tc/loader1.gif"></div>');
	},
	show:function(num) {
		$('.index_properties .loader').remove();
		$('.index_properties #index_properties_box' + properities_box.current + ' .img').cycle('destroy');
		$('.index_properties .properties_box').hide();
		$('.index_properties #index_properties_box' + num).fadeIn('middle');
		$('.index_properties #index_properties_box' + num + ' .img').cycle({
			fx: 'fade',
			timeout: 8000,
			slideExpr: 'img',
			before: function (curr, next, opts) {
				var index = $(next).parent('a').index();
				$('.index_properties #index_properties_box' + num + ' .menu li a').removeClass('current');
				$('.index_properties #index_properties_box' + num + ' .menu li:not(".more") a:eq(' + index + ')').addClass('current');
			}
		});
		$('.index_properties #index_properties_box' + num + ' .menu li:not(".more") a').mouseover(function () {
			$('.index_properties .properties_box .img').cycle($(this).parent('li').index());
			return false;
		});
		
		$('.index_properties #index_properties_box' + num + ' .menu li.more a').mouseout(function () {
			$('.index_properties #index_properties_box' + num + ' .menu li a').removeClass('current');
			return false;
		});
		
		$('.index_properties #index_properties_box' + num + ' .menu li.more a').mouseover(function () {
			$('.index_properties #index_properties_box' + num + ' .menu li a').removeClass('current');
			$(this).addClass('current');
			return false;
		});
		
		properities_box.current = num;
	}
	
}


/* Director Effect */
// lith: rewrote to support binding after dynamic load

var director = {
    init: function () {
        $('div.director_box .post .title').hide();
        $('div.director_box .box1').css({
            border: 'none',
            margin: '10px 0',
            padding: '0',
            background: 'none',
            width: 'auto'
        });
        $('div.director_box .box1 p').css('margin', '0 0 10px 0').css('padding', '0');
        $('div.director_box .name').click(this.clickme);
    },
    clickme: function () {
        var me = $(this);
        var myparent = me.parent("div.director_box");
        if (me.hasClass("current")) {
            me.removeClass("current");
            myparent.find(".box1,.box_upcoming").slideUp('middle');
            myparent.find(".post .title").slideUp('middle');
        } else {
            me.addClass("current");

            var h = myparent.find(".box1,.box_upcoming").height();
            var h2 = myparent.find(".post .title").height();
            myparent.find(".box1,.box_upcoming").css("height", "0px").animate({
                "height": h + "px"
            }, "middle", function () { $(this).css("height", "auto") });
            myparent.find(".post .title").css("height", "0px").animate({
                "height": h2 + "px"
            }, "middle", function () { $(this).css("height", "auto") });

            //myparent.find(".post .title").show();
            //myparent.find(".box1").slideDown('middle')
        }
        myparent.siblings("div.director_box").find(".name").removeClass("current");
        myparent.siblings("div.director_box").find(".box1,.box_upcoming").slideUp('middle');
        myparent.siblings("div.director_box").find(".post .title").slideUp('middle');
    }
}


/* properties */
// lith: rewrote to support binding after dynamic load
var properties={
	height:{
		"lite":[],
		"full":[]
	},
	init:function(){
		var rel=$('.content .box2:eq(0)').attr("rel");
		this.height["lite"]=[];
		this.height["full"]=[];
		$('.content .box2').each(function(){
			var mybox=$(this);
			properties.height["lite"][rel]=mybox.find(".lite").height();
			properties.height["full"][rel]=mybox.find(".full").height();
			mybox.find(".full").hide().css({'position':'static','visibility':'visible'});
			mybox.find(".detail, .detail a").click(function () { properties.expand(mybox.attr("rel")) });
			mybox.find(".summary, .summary a").click(function () { properties.expand(mybox.next().attr("rel")); });
			mybox.find(".box2-header h2, .box2-content .lite img:not(.logo)").click(function(){
				if (mybox.hasClass("opened")){
					properties.shrink(mybox.attr("rel"))
				}else{
					properties.expand(mybox.attr("rel"))
				}
			});
		});
		
		if($('.content .box2').length>0){

			//take value from anchor, name='properties':
			if (typeof(anchor.parameter["properties"])!="undefined"){
				rel=anchor.parameter["properties"];
				$.scrollTo($('.content .box2[rel='+rel+']'));
//				delete(anchor.parameter["properties"]); // remove after use
				this.expand(rel);
            }else if(typeof(anchor.parameter["more"])!="undefined"){
				rel=anchor.parameter["more"];
				$.scrollTo($('.content .box2[rel='+rel+']'));
            }
		}
	},
	
	expand:function(index){
		$('.content .box2[rel='+index+']').addClass('opened');
		
		var from="lite";
		var to="full";
		this.shrinkAllother(index);
		this.display_detail(index, null, from, to);
		return false;
	},
	
	shrink:function(index){
		var box=$('.content .box2[rel='+index+']');
		if (box.hasClass("opened")){
			box.removeClass('opened');
			var from="full";
			var to="lite";
			this.display_detail(index, null, from, to);
		}
		return false;
	},
	
	shrinkAllother:function(index){
		$('.content .box2').each(function(){
			var mybox=$(this);
			if (parseInt(mybox.attr("rel"))!=parseInt(index)){
				properties.shrink(mybox.attr("rel"));
			}
		});
	},
	
	display_detail:function (index, height, from, to){
//		console.log(index+": "+from+"->"+to);
		$('.content .box2[rel='+index+'] .'+from).fadeOut('middle',function(){
			properties.animate(index, height, from, to);
		});
	},
	
	animate: function (index, height, from, to){
		var setheight={
			"lite":$('.content .box2[rel='+index+'] .lite').height(),
			"full":$('.content .box2[rel='+index+'] .full').height()
		}
//		console.dir(setheight);
		

		var padding=30;
		$('.content .box2[rel='+index+'] .'+from).after('<div style="height: '+setheight["lite"]+'px;" class="loader"><img class="loader1" src="'+xpath.img+'/loader1.gif"></div>');
		$('.content .box2[rel='+index+']').animate({
			height: $('.content .box2[rel='+index+'] .'+to).height() *0.9
		}, 1000, function() {
			$('.content .box2[rel='+index+'] .'+from).hide();
			$('.content .box2 .loader').remove();
			$('.content .box2[rel='+index+'] .'+to).fadeIn('middle');
			$('.content .box2[rel='+index+']').animate({
				height: $('.content .box2[rel='+index+'] .'+to).height() + padding
			}, 400, function(){$(this).css("height","auto")});
		});

//		$('.content .box2[rel='+index+'] .full').show();
//		$('.content .box2[rel='+index+'] .lite').show();
//		console.log($('.content .box2[rel='+index+'] .full').height());
	}
	
}



var stock={

	getid:function(){
		var temp=$.cookie("SHK_realtimeStock");
		return((temp!=null)?temp:"");
	},
	setid:function(){
		$.cookie("SHK_realtimeStock", "true", cookieSetting);
	},
	
	subscribe:function(){
		this.setid();
		location.reload();
	},
	
	init:function(){
		if ($(".stock").length>0){
			if (this.getid()!=""){
				var url="/RealTimeStockQuote.xml";
				$("tr.delayquote").hide();
				$("tr.realtimequote").show();
			}else{
				var url="/stockquote.xml";
			}
			$.ajax({ 
				url:url, 
				type: 'get', 
				datatype: ($.browser.msie) ? "text" : "xml",
				error: function(XMLHttpRequest, textStatus, errorThrown){ 
					  alert('error loading xml document :'+textStatus); 
				}, 
				success: this.loaded
				
			}); 
			$("#chartInput input[name=draw]").click(stock.chart);
			$("#chartInput input[name=draw]").click();
		}
	},
	
	loaded:function(strXML){
		var xml;
		try {
			xml = new ActiveXObject("Microsoft.XMLDOM");
			xml.async = false;
			xml.loadXML(strXML);
		} catch(e){
			xml = strXML;
		}
		
		var items =["Last", "Bid", "Ask", "Change", "ChangeRate", "Open", "High", "Low", "PreClose", "Volume", "Turnover", "PE", "Yield", "YearHigh", "YearLow", "Lotsize", "MktCap", "Date", "Time"];


		for (var i in items){
			var value=$(xml).find(items[i]).text();
			if ((items[i]!="Lotsize")&&(items[i]!="Date")){
				if (parseFloat(value,10)>=1000){
					value=Math.round(parseFloat(value,10)/1000);
					for(var text="";value>1000;text=","+value%1000+text,value=Math.floor(value/1000));
					value=""+value+text+"K";
				}
			}
			$("span.xml_"+items[i]).html(value);
		}
		
		
	},
	
	chart:function(){
		var form=$("#chartInput");
		var image=$("img.stockChart");
		var today=new Date();
		var obj={
			blen:"",
			sd:"",
			mon_len:"",
			macdlen1:"",
			macdlen2:"",
			macdAvg:"",
			k:"",
			d:"",
			c_code:"",
			code:16
		};
		obj["e_day"]=formatDate(today);
		obj["s_day"]=function(){
			switch(form.find("[name=TimeSpan]").attr("value")){
				case "TIME00": return(formatDate(today, {"m":-1}));
				case "TIME01": return(formatDate(today, {"m":-6}));
				case "TIME02": return(formatDate(today, {"y":-1}));
				case "TIME03": return(formatDate(today, {"y":-1}));
				case "TIME04": return(formatDate(today, {"y":-3}));
				case "TIME05": return(formatDate(today, {"y":-3}));
				case "TIME06": return(formatDate(today, {"y":-5}));
				case "TIME07": return(formatDate(today, {"y":-5}));
				case "TIME08": return(formatDate(today, {"y":-10}));
			}
		}.call();
		obj["period"]=function(){
			switch(form.find("[name=TimeSpan]").attr("value")){
				case "TIME00":
				case "TIME01":
				case "TIME02": return("daily");
				case "TIME03":
				case "TIME04":
				case "TIME06": return("weekly");
				case "TIME05":
				case "TIME07":
				case "TIME08": return("monthly");
			}
		}.call();
		obj["type"]=form.find("[name=ChartType]").attr("value");
		
		obj["u_fun"]=form.find("[name=UpperFunction]:checked").attr("value");
		obj["l_fun"]=form.find("[name=LowerFunction]:checked").attr("value");
		obj["mlen_a"]=form.find("[name=mov1]").attr("value");
		obj["mlen_b"]=form.find("[name=mov2]").attr("value");
		obj["mlen_c"]=form.find("[name=mov3]").attr("value");
		obj["rsi"]=form.find("[name=rsi]").attr("value");


		if (obj["u_fun"]=="none") delete(obj["u_fun"]);
		if (obj["l_fun"]=="none") delete(obj["l_fun"]);




		var query=[];
		for (var key in obj){
			query.push(key+"="+obj[key]);
		}
		

		
		image.attr("src", "http://fif2.e-finet.net/shk/QuoteChart/drawTechChart.php?"+query.join("&")).show();
		
	}
	
}



/* ============================================================================================================*/
/* =========================================== Helper functions ===============================================*/
/* ============================================================================================================*/
// smooth scrolling
$.scrollTo = function(selector){
	$('html, body').animate({scrollTop:$(selector).offset().top}, 'fast');
}

$.preLoadImages = function() {
	var cache = [];
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
    }
}

//source: http://plugins.jquery.com/project/cookie
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
//				console.log("cookie "+i+" = "+cookie);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



var linkTable=function(option){
	
	if (typeof(linkTable_timer)!="undefined") clearTimeout(linkTable_timer);
	if ($(option.table).length>0){
		var root=$(option.select).empty();
		$("<option>").attr("value","").html(option.text).appendTo(root);
		$(option.table+" tbody tr").find("td:first").not(".footer").each(function(){
			var content=$(this).html().trim().split("-");
			
			if (root.find("[value='"+content[2]+"']").length==0){
				$("<option>").attr("value",content[2]).html(content[2]).appendTo(root);
			}
		});
		
		root.change(function(){
			var value=$(this).attr("value");
			if (value!=""){
				$(option.table+" tbody tr").find("td:first").not(".footer").parents("tr").hide().each(function(){
					if($(this).find("td:eq(0):contains("+value+")").length>0) $(this).show();
				});
			}else{
				$(option.table+" tbody tr").find("td:first").not(".footer").parents("tr").show();
			}
		});
		
		$(option.table+" tbody tr").find("td:first").not(".footer").parents("tr").hide();
		$(option.table+" tbody tr:lt(5)").find("td:first").not(".footer").parents("tr").show();
		
	}else{
		linkTable_timer=setTimeout(function(){linkTable(option);}, 300);
	}
}


String.prototype.trim=function(){

	var objRegExp = /^(\s*)$/;
	var strValue = this;
	
	//check for all spaces
	if(objRegExp.test(strValue)) {
		strValue = strValue.replace(objRegExp, '');
		if( strValue.length == 0) return strValue;
	}
	
	//check for leading & trailing spaces
	objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
	if(objRegExp.test(strValue)) {
	//remove leading and trailing whitespace characters
		strValue = strValue.replace(objRegExp, '$2');
	}
	
	return strValue;
	
}




var formatDate=function (dat){
	if (typeof(dat)=="string"){
		return(dat);
	}else{
		var offset={"y":0,"m":0,"d":0,"hr":0,"min":0,"sec":0,"msec":0};
		if (arguments.length>1){
			for(var i in arguments[1]){
				offset[i]=arguments[1][i];
			}
		}

		var ndate=new Date(
		   dat.getFullYear()+offset.y,
		   dat.getMonth()+offset.m,
		   dat.getDate()+offset.d,
		   dat.getHours()+offset.hr,
		   dat.getMinutes()+offset.min,
		   dat.getSeconds()+offset.sec,
		   dat.getMilliseconds()+offset.msec
		);

		var year=(ndate.getYear()<1000)?(ndate.getYear()+1900):ndate.getYear();
		var month=("00"+(ndate.getMonth()+1)).slice(-2);
		var day=("00"+ndate.getDate()).slice(-2);
		return(year+"-"+month+"-"+day);
	}
}

var realsize=function(obj){
	var w_css=["margin-left", "border-left-width", "padding-left", "padding-right", "border-right-width", "margin-right"];
	var h_css=["margin-top", "border-top-width", "padding-top", "padding-bottom", "border-bottom-width", "margin-bottom"];
	
	var h=parseInt($(obj).height());
	var w=parseInt($(obj).width());
	for (var i=0;i<h_css.length;i++){
		var temp=parseInt($(obj).css(h_css[i]));
		if (!isNaN(temp)) h+=temp;
	}
	for (var i=0;i<w_css.length;i++){
		var temp=parseInt($(obj).css(w_css[i]));
		if (!isNaN(temp)) w+=temp;
	}
	return({"h":h, "w":w});
}


var propertyDropDown = {
		init:function(){
			content = '<label><select name="select"  class="mainland_dropdown" onchange="window.open(this.options[this.selectedIndex].value,\'_top\')"><option value="#" selected>其他內地項目</option><option value="#">----------------------------------------------</option></select></label>'; 
			$("#mainland_property_dropdown").html(content);
			$.ajax({
				url: "/content/xml/city_dropdown.xml",
				dataType: "html",
				success: function(data){
						var dummy = data;
						if (jQuery.browser.msie) {
							var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
							xmlDoc.loadXML(dummy);
							dummy = $(xmlDoc).children();
						}
						content = "";
						$(dummy).find("region").each(function(){
							dummyContetn = $(this);
							content += '<optgroup label="'+dummyContetn.children("label").children("tc").text()+'">';
							dummyContetn.find("building").each(function(){
								content += '<option value="/'+currentCulture+$(this).find("url").text()+'">'+$(this).find("tc").text()+'</option>';
							})
							content += '</optgroup>';
						})
						$(".dropdown .mainland_dropdown").append(content);
					}
				})
		}		
}

function flash_typeSelected(id){
	if ($("#property-map").length > 0) {
		switch (id) {
			case "1":
				str = $("#property-map").children("param[name='flashvars']").attr("value").split("/")
				if (str[str.length - 2] == "hong-kong-property-map") {
					$("#T12345").remove();
					$("#property-map").after("<div id=\"T12345\">註: 主要住宅物業包括銷售中及出租的物業</div>");
				}
				break;
			default:
				$("#T12345").remove();
				break;
		}
	}
	//alert(id)
}
//calendar_thung_shing
// JavaScript Document
