// JScript File
var QuickLook_i = 1;
var QuickLook_w = 0;
var QuickLook_h = 0;
var QuickLook_quickLookWindow;
var QuickLook_QuickLook;
var QuickLook_ImageWidth = 115;
var QuickLook_ImageHeight = 144;
var QuickLook_labelwidth = 75;
var QuickLook_labelheight = 26;
var QuickLook_divheight = 500;
var QuickLook_divwidth = 725;
var QuickLook_divlength = 725;
var QuickLook_Imglook;
var QuickLook_imgurl;
var QuickLook_opened = false;
var QuickLook_initdrag = false;
var QuickLook_url;
var QuickLook_isFF = false;
var full = true;
var clang = '';

function QuickLook_TreeViewFadeIn()
{                 
    QuickLook_quickLookWindow.style.width = QuickLook_divwidth + "px";
    QuickLook_quickLookWindow.style.height = QuickLook_divheight + "px";                            
    var closebtn = QuickLook_quickLookWindow.getElementsByTagName("img");        
    var divframe = QuickLook_quickLookWindow.getElementsByTagName("iframe");
    divframe[0].style.visibility = "visible";
    closebtn[0].style.visibility = "visible";          
    if (full)
    {
        QuickLook_QuickLook.style.visibility= "hidden";        
        QuickLook_Imglook.style.visibility = "hidden"; 
    }       
}
function QuickLook_TreeViewFadeOut(id)
{                      
    QuickLook_quickLookWindow.style.visibility = "hidden";                
    QuickLook_opened = false;     
    QuickLook_initdrag = false; 
    document.body.removeChild(QuickLook_quickLookWindow);
    QuickLook_quickLookWindow = null;        
    if (tooltip)
    {
        document.body.removeChild(tooltip);
        tooltip.style.visibility = "hidden";
        tooltip = null;
    }
    if (quickview) {
        var olddivid = "QuickView_" + quickview.id;
        var oldcontainer = document.getElementById(olddivid);
        oldcontainer.removeChild(quickview);
        quickview.style.visibility = "hidden";
        quickview = null;
    }
    if (id != null && id != "undefined")   
    {                        
        if (full)
            CreateQuickLookWindow();
        else
            ShowQuickLookWindow();
    } 
}

function imgmouseover(oimg,imgurl)
{
  var img = document.getElementById(oimg);
  if( img == null )  
     return;
  img.src = imgurl;    
}

function imgmouseout(oimg)
{
    var img = document.getElementById(oimg);
    if( img == null )    
        return;
    var orgurl = img.getAttribute("_origurl");
    img.src = orgurl;
}

function QuickLook_switchImage(oimg, over) {
    var img = document.getElementById(oimg);
    _origurl = img.getAttribute("_origurl");
    _switchurl = img.getAttribute("_switchurl");

    if (_switchurl != null)
        if (over)
        img.src = _switchurl;
    else
        img.src = _origurl;
}

function SetLang(lang) {
    clang = lang;
}

function QuickLook_openQuickLookLauncher(label, img, obj, divw, divh, imglink, bshowquick)
{    
    if (QuickLook_opened && QuickLook_quickLookWindow.id == label)            
        return;        
    
    var sAgent = navigator.userAgent.toLowerCase();    
    QuickLook_isFF = (sAgent.indexOf("ie") ==-1);//firefox 
    full = true;
    QuickLook_QuickLook = document.getElementById(label);
    
    var o = document.getElementById(obj);
    QuickLook_ImageWidth = o.width;
    QuickLook_ImageHeight = o.height;    
    QuickLook_url = o.getAttribute("_url");
    
    QuickLook_divwidth = divw;
    QuickLook_divheight = divh;    
    if (divw > divh)
        QuickLook_divlength = divw;
    else
        QuickLook_divlength = divh;
    QuickLook_Imglook = document.getElementById(img);    
    QuickLook_imgurl = imglink;     
    SetLabelSrc(bshowquick);           
    if (QuickLook_ImageWidth >= 76)
    {
        QuickLook_QuickLook.style.top = QuickLook_ImageHeight * 2 / 3 + "px";
        QuickLook_QuickLook.style.left = (QuickLook_ImageWidth - 76 )/ 3 + "px";   
    }
    else
    {        
        QuickLook_QuickLook.style.top = (QuickLook_ImageHeight - 25) / 2 + "px";
        QuickLook_QuickLook.style.left = (QuickLook_ImageWidth - 25) / 2 + "px";
    }
         
    QuickLook_QuickLook.style.visibility = "visible";            
}
function SetLabelSrc(bshowquick) {    
    if (QuickLook_ImageWidth > QuickLook_labelwidth && QuickLook_ImageHeight > QuickLook_labelheight)
    {        
        QuickLook_Imglook.className = "QuickLookOver" + clang;
        QuickLook_Imglook.style.height = QuickLook_labelheight + "px";
        QuickLook_Imglook.style.width = QuickLook_labelwidth + "px";
        QuickLook_QuickLook.style.height = QuickLook_labelheight + "px";
        QuickLook_QuickLook.style.width = QuickLook_labelwidth + "px";
    }
    else
    {     
        QuickLook_Imglook.className = "QuickLookSimpleOver";
        QuickLook_Imglook.style.height = "25px";
        QuickLook_Imglook.style.width = "25px";
        QuickLook_QuickLook.style.height = "25px";
        QuickLook_QuickLook.style.width = "25px";
    }
    if( bshowquick )
        QuickLook_Imglook.style.visibility = "visible";
}

function closedivQuickLook(event)
{
    if (!QuickLook_QuickLook || !QuickLook_Imglook)
        return;
    QuickLook_QuickLook.style.visibility= "hidden";
    QuickLook_Imglook.style.visibility = "hidden";
}

function closeQuickLook(event)
{   
    if (!QuickLook_QuickLook || !QuickLook_Imglook)
        return;
    var x;
    var y;
    var o;        
    if (QuickLook_isFF)
    {
        x = event.layerX;
        y = event.layerY;            
        o = event.target; 
    }
    else
    {        
	    x = window.event.offsetX;
	    y = window.event.offsetY;
	    o = window.event.srcElement;
	}                   	
		
    if (x <= 0 || x >= QuickLook_ImageWidth || y <= 0 || y >= QuickLook_ImageHeight)
    {
        if (QuickLook_QuickLook != null)            
        {
            QuickLook_QuickLook.style.visibility= "hidden";
            QuickLook_Imglook.style.visibility = "hidden";
        }
    }
}
function QuickLook_mouseup() {
    var cls = QuickLook_Imglook.className;
    cls = cls.replace('Over', 'On');    
    QuickLook_Imglook.className = cls;
}
function QuickLook_mouseout() {   
    var cls = QuickLook_Imglook.className;
    cls = cls.replace('On', 'Over');
    QuickLook_Imglook.className = cls;
}
function QuickLook_mousedown() {
    var cls = QuickLook_Imglook.className;
    cls = cls.replace('On', 'Down');
    QuickLook_Imglook.className = cls;
}

function QuickLook_launchQuickLook(event)
{        
    if (!QuickLook_Imglook || !QuickLook_QuickLook)
        return;
    
    if (QuickLook_QuickLook.style.visibility != "visible")
        return;

    if (QuickLook_Imglook.className.indexOf("Down") == -1)
        return;
    
    if (QuickLook_quickLookWindow == 'undefined' || QuickLook_quickLookWindow == null)
        CreateQuickLookWindow();
    else
        closediv(QuickLook_QuickLook.id);
}

function CreateQuickLookWindow()
{    
    QuickLook_quickLookWindow = document.createElement('div');    
    QuickLook_quickLookWindow.style.position = "absolute";
    QuickLook_quickLookWindow.style.visibility = "hidden";
    QuickLook_quickLookWindow.style.width = "0px";
    QuickLook_quickLookWindow.style.height = "0px"; 
    QuickLook_quickLookWindow.style.overflow = "visible"; 
    QuickLook_quickLookWindow.style.backgroundColor = "#ffffff";    
    QuickLook_quickLookWindow.style.borderColor = "Gray";
    QuickLook_quickLookWindow.style.borderWidth = "3px";
    QuickLook_quickLookWindow.style.padding = "3px 3px 3px 3px";
    QuickLook_quickLookWindow.style.borderStyle = "solid";
    QuickLook_quickLookWindow.style.zIndex = 100002;
    QuickLook_quickLookWindow.id = QuickLook_QuickLook.id;        
                        
    var content = "<div style=\"position: absolute; top: 10px; right:10px; z-index:2\">";
    content += "<img id=\"closebtn\" style=\"visibility:hidden;\" src=\"" + QuickLook_imgurl + "/quickLook_close.GIF\" onclick=\"closediv();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
    content += "</div>";    
    //content += "<div id=\"divmove\" style=\"background-color:#e1e1e1;cursor:move; height:15px;\"><center id=\"divmove\">Drag Me...</center></div>";
    content += "<div style=\"width:725px; height:495px;\" id=\"divframe\">";
    content += "<iframe src=\"" + QuickLook_url + "\" frameborder=\"0\" scrolling=\"no\" style=\"display:block; visibility:hidden;width: 100%;height: 100%;\"></iframe>";
    content += "</div>";
    QuickLook_quickLookWindow.innerHTML = content;
    document.body.appendChild(QuickLook_quickLookWindow);
    OpenQuickLookWindow()   
}
function OpenQuickLookWindow()
{
    var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);        

    var clientWidth;
    var clientHeight;
    switch (Sys.Browser.agent) {
        case Sys.Browser.InternetExplorer:
            clientWidth = document.documentElement.clientWidth;
            clientHeight = document.documentElement.clientHeight;
            break;
        case Sys.Browser.Safari:
            clientWidth = window.innerWidth;
            clientHeight = window.innerHeight;
            break;
        case Sys.Browser.Opera:
            clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
            clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
            break;
        default:  // Sys.Browser.Firefox, etc.
            clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
            clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
            break;
    }

    var xCoord = 0;
    var yCoord = 0;

    var foregroundelementwidth = QuickLook_quickLookWindow.offsetWidth ? QuickLook_quickLookWindow.offsetWidth : QuickLook_quickLookWindow.scrollWidth;
    xCoord = ((clientWidth - foregroundelementwidth) / 2);
    xCoord += scrollLeft;
    xCoord -= Number(QuickLook_divwidth) / 2;
    QuickLook_quickLookWindow.style.left = xCoord + 'px';
    var foregroundelementheight = QuickLook_quickLookWindow.offsetHeight ? QuickLook_quickLookWindow.offsetHeight : QuickLook_quickLookWindow.scrollHeight;
    yCoord = ((clientHeight - foregroundelementheight) / 2);
    yCoord += scrollTop;
    yCoord -= Number(QuickLook_divheight) / 2;
    QuickLook_quickLookWindow.style.top = yCoord + 'px';    
    QuickLook_quickLookWindow.style.visibility = "visible";                    
    QuickLook_TreeViewFadeIn();            
    QuickLook_opened = true;
}

function documentClick(event)
{                     
    var x;
    var sAgent = navigator.userAgent.toLowerCase();    
    var QuickLook_isFF = (sAgent.indexOf("ie") ==-1);//firefox 
    if (!QuickLook_isFF)
        x = window.event.srcElement;    
    else
        x = event.target; 
    
    if (typeof(HideShoppingBag) == "function")
        HideShoppingBag();
    
    if (QuickLook_quickLookWindow != null && QuickLook_quickLookWindow.style.visibility == "visible")
        closediv();
    if (tooltip)
    {
        document.body.removeChild(tooltip);
        tooltip.style.visibility = "hidden";
        tooltip = null;
    }
    if (quickview) {
        var olddivid = "QuickView_" + quickview.id;
        var oldcontainer = document.getElementById(olddivid);
        oldcontainer.removeChild(quickview);
        quickview.style.visibility = "hidden";
        quickview = null;
    }
}

function closediv(id)
{                             
    var closebtn = QuickLook_quickLookWindow.getElementsByTagName("img");        
    var divframe = QuickLook_quickLookWindow.getElementsByTagName("iframe");
    divframe[0].style.visibility = "hidden";
    closebtn[0].style.visibility = "hidden";        
    if (QuickLook_i <= 0)
        QuickLook_i = 20;    
    QuickLook_TreeViewFadeOut(id);  
    var formclosebtn = parent.document.getElementById("formclosebtn");         
    if (formclosebtn)
    {        
        formclosebtn.style.display = "block";
    }      
}

var tooltip;
var quickview;
var QuickLook_style;
var QuickLook_color;
var simplex = 0;
var simpley = 0;
var objectid;

function showQuickView(style, color, fromobj, fromref, obj) {
    var w = obj.clientWidth;
    var h = obj.clientHeight;
    var imgid = obj.id;
    var divid = "QuickView_" + imgid;
    var container = document.getElementById(divid);
    if (w >= 76) {        
        simpley = h * 2 / 3 + "px";
        simplex = (w - 76) / 3 + "px";
    }
    else {
        simpley = (h - 25) / 2 + "px";
        simplex = (w - 25) / 2 + "px";
    }
    var curl = document.URL;
    var hn = document.location.host;

    curl = curl.replace("http://" + hn + "/", "");
    var a = curl.split('/');
    var app = "";
    if (a.length > 2) {
        app = a[0] + "/";
    }
    var simpleurl = "http://" + hn + "/" + app + "QuickLookPage.aspx?product={0}&color={1}&fromid={2}&fromref={3}";

    QuickLook_url = simpleurl.replace("{0}", style);
    QuickLook_url = QuickLook_url.replace("{1}", color);
    QuickLook_url = QuickLook_url.replace("{2}", fromobj);
    QuickLook_url = QuickLook_url.replace("{3}", fromref);
    if (QuickLook_quickLookWindow) {
        if (QuickLook_style == style && QuickLook_color == color)
            return;
    }

    QuickLook_style = style;
    QuickLook_color = color;
    if (quickview) {
        var olddivid = "QuickView_" + quickview.id;
        var oldcontainer = document.getElementById(olddivid);
        oldcontainer.removeChild(quickview);
        quickview.style.visibility = "hidden";
        quickview = null;
    }
    quickview = document.createElement('div');
    quickview.style.position = "absolute";
    quickview.style.width = "75px";
    quickview.style.height = "26px";
    quickview.style.overflow = "visible";
    quickview.style.backgroundColor = "Transparent";
    quickview.style.zIndex = "9999";
    quickview.id = imgid;
    var content = "<img id=\"tooltipicon\" src=\"PublicImg/FittingRoom/Transparent.gif\" class='QuickLookOver' onmouseout=\"javascript:ImgMouseOut(this);\" onmouseover=\"javascript:ImgMouseUp(this);\" onmousedown=\"javascript:ImgMouseDown(this);\" onclick=\"QuickLook_ShowQuickLook('" + style + "','" + color + "');\" style=\"cursor: hand;\" />";
    quickview.innerHTML = content;
    quickview.style.top = simpley;
    quickview.style.left = simplex;
    container.insertBefore(quickview, null);

    var url = obj.getAttribute('_origurl');    
    obj.src = url.replace(color + '_1_2', color + '_2_0');
    
    if (document.all) {
        container.attachEvent("onmouseout", function() { CloseQuickView(imgid, w, h, event); imgonerror(obj.id); });
        obj.attachEvent("onerror", function() { imgonerror(obj.id) });        
    }
    else {
        container.addEventListener("mouseout", function() { CloseQuickView(imgid, w, h, event); imgonerror(obj.id); }, false);
        obj.addEventListener("error", function() { imgonerror(obj.id) }, false);
    }
}

function ImgMouseUp(obj) {
    var cls = obj.className;
    cls = cls.replace('Over', 'On');
    obj.className = cls;
}
function ImgMouseOut(obj) {
    var cls = obj.className;
    cls = cls.replace('On', 'Over');
    obj.className = cls;
}
function ImgMouseDown(obj) {
    var cls = obj.className;
    cls = cls.replace('On', 'Down');
    obj.className = cls;
}

function imgonerror(imgid) {
    var img = document.getElementById(imgid);
    var osrc = img.getAttribute("_origurl");
    img.src = osrc;
}

function CloseQuickView(id,w,h,event) {
    if (quickview) {
        if (quickview.id == id) {
            var x;
            var y;            
            if (!document.all) {
                x = event.layerX;
                y = event.layerY;                
            }
            else {
                x = window.event.offsetX;
                y = window.event.offsetY;                
            }

            if (x <= 0 || x >= w || y <= 0 || y >= h) {
                var olddivid = "QuickView_" + quickview.id;
                var oldcontainer = document.getElementById(olddivid);
                oldcontainer.removeChild(quickview);
                quickview.style.visibility = "hidden";
                quickview = null;

                if (document.all)
                    oldcontainer.detachEvent("onmouseout");
                else
                    oldcontainer.removeEventListener("mouseout");
            }        
        }
    }    
}

function showtooltip(style, color, fromobj, fromref, event, mode, size, objid, qty, hidid, uptid, para)
{    
    var sAgent = navigator.userAgent.toLowerCase();  
    QuickLook_isFF = (sAgent.indexOf("ie") ==-1);
    objectid = objid;
    if(QuickLook_isFF)
    {
        simplex=event.layerX;
        simpley=event.layerY;
    }
    else
    {        
        simplex=document.documentElement.scrollLeft +event.clientX;
        simpley=document.documentElement.scrollTop +event.clientY;
    }
    var curl = document.URL;
    var hn = document.location.host;
    
    curl = curl.replace("http://" + hn + "/", "");    
    var a = curl.split('/');
    var app = "";
    if (a.length > 2)
    {
        app = a[0] + "/";
    }
    var simpleurl = "http://" + hn + "/" + app + "QuickLookPage.aspx?product={0}&color={1}&fromid={2}&fromref={3}";
    
    QuickLook_url = simpleurl.replace("{0}", style);
    QuickLook_url = QuickLook_url.replace("{1}", color);
    QuickLook_url = QuickLook_url.replace("{2}", fromobj);
    QuickLook_url = QuickLook_url.replace("{3}", fromref);
    if (mode != null && mode.length > 0)
        QuickLook_url += "&mode=" + mode;
        
    if (size != null && size.length > 0)
        QuickLook_url += "&size=" + size;
    
    if (qty != null && qty.toString().length > 0)
        QuickLook_url += "&qty=" + qty;
        
    if (hidid != null)
        QuickLook_url += "&hidid=" + hidid;
    
    if (uptid != null)
        QuickLook_url += "&uptid=" + uptid;
        
    if (para != null && para.toString().length > 0)
        QuickLook_url += "&parameter=" + para;
    
    if (QuickLook_quickLookWindow)
    {        
        if (QuickLook_style == style && QuickLook_color == color)
            return;     
    }         
    
    QuickLook_style = style;
    QuickLook_color = color;  
    
    if (tooltip)
    {   
        document.body.removeChild(tooltip);     
        tooltip.style.visibility = "hidden";
        tooltip = null;           
    }        
    if(mode == null || mode.length == 0)
    {
        tooltip = document.createElement('div');    
        tooltip.style.position = "absolute";        
        tooltip.style.width = "75px";
        tooltip.style.height = "26px"; 
        tooltip.style.overflow = "visible"; 
        tooltip.style.backgroundColor = "Transparent";
        tooltip.style.zIndex = "9999";  
        tooltip.id = "tooltipimg" + style + color;      
        var content = "<img id=\"tooltipicon\" src=\"PublicImg/button_quicklook_launcher_over.gif\" onclick=\"QuickLook_ShowQuickLook('" + style + "','" + color + "');\" style=\"cursor: hand;\" />";    
        tooltip.innerHTML = content;
        tooltip.style.top = simpley + "px";
        tooltip.style.left = simplex + "px";
        document.body.insertBefore(tooltip, null);     
    }
    else
    {       
        if (document.readyState)
        {    
            if (document.readyState == "complete")                
                QuickLook_ShowQuickLook(style, color);       
            else
            {            
                if (document.all)  
                    window.attachEvent("onload",function() {QuickLook_ShowQuickLook(style, color);});  
                else  
                    window.addEventListener("load",function() {QuickLook_ShowQuickLook(style, color);},false); 
            }
        }
        else
            QuickLook_ShowQuickLook(style, color);       
    }
}

function QuickLook_ShowQuickLook(style, color)
{                    
    full = false;     
    if (QuickLook_quickLookWindow == 'undefined' || QuickLook_quickLookWindow == null)
    {             
        ShowQuickLookWindow();
    }
    else         
        closediv(style + color);    
}

function ShowQuickLookWindow()
{                                      
    QuickLook_quickLookWindow = document.createElement('div');    
    QuickLook_quickLookWindow.style.position = "absolute";
    QuickLook_quickLookWindow.style.visibility = "hidden";
    QuickLook_quickLookWindow.style.width = "0px";
    QuickLook_quickLookWindow.style.height = "0px"; 
    QuickLook_quickLookWindow.style.overflow = "visible"; 
    QuickLook_quickLookWindow.style.backgroundColor = "#ffffff";    
    QuickLook_quickLookWindow.style.borderColor = "Gray";
    QuickLook_quickLookWindow.style.borderWidth = "3px";
    QuickLook_quickLookWindow.style.padding = "3px 3px 3px 3px";
    QuickLook_quickLookWindow.style.borderStyle = "solid";
    QuickLook_quickLookWindow.style.zIndex = 100002;
    QuickLook_quickLookWindow.id = QuickLook_style + QuickLook_color;        
    var content = "<div style=\"position: absolute; top: 10px; right:10px; z-index:2\">";
    content += "<img id=\"closebtn\" style=\"visibility:hidden;\" src=\"http://www.e-giordano.com/PublicImg/quickLook_close.GIF\" onclick=\"closediv();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
    content += "</div>";        
    content += "<div style=\"width:725px; height:495px;\" id=\"divframe\">";
    content += "<iframe id=\"iframe1\" src=\"" + QuickLook_url + "\" frameborder=\"0\" scrolling=\"no\" style=\"display:block;visibility:hidden;width: 100%;height: 100%;\"></iframe>";
    content += "</div>";        
    QuickLook_quickLookWindow.innerHTML = content;
    //document.body.insertBefore(QuickLook_quickLookWindow,null); 
    document.body.appendChild(QuickLook_quickLookWindow);
    
    var formclosebtn = parent.document.getElementById("formclosebtn");         
    if (formclosebtn)
    {        
        formclosebtn.style.display = "none";
    }
    OpenQuickLookWindow();      
}


function UpdateStyleColor(result, hidid, btnid)
{
    var hid = document.getElementById(hidid);
    if (hid == null)
        return;
    hid.value = result;
    
    var btn = document.getElementById(btnid);
    if (btn == null)
        return;
    btn.click();
}
var ispause = false;
function ShowKeyLookView(imgid, url, btnid, nextid, cnt)
{
    var img = $get(imgid);
    var btn = $get(btnid);
    var next = $get(nextid);        
    
    if (img && btn && next)
    {        
        var stopimg = "PublicImg/rollingbar_play.jpg";
        var playimg = "PublicImg/rollingbar_pause.jpg";
        var curimg = btn.src.toString().toLowerCase();                
        if (curimg.indexOf(stopimg.toLowerCase(), 0) == -1)
        {                        
            ispause = true;
            btn.click();                        
        }
        var imgurl = img.src.toString();                
        var sletter = imgurl.substr(imgurl.length - 5, 1);
        var tletter = url.substr(url.length - 5, 1);
        var lcnt = 8;
        lcnt = Number(tletter) - Number(sletter);
        if (lcnt < 0)
            lcnt = Number(cnt) + Number(lcnt);        
        for (var i = 0; i < lcnt; i++)
        {    
            next.click();                   
        }        
        if (ispause)                 
        {
            btn.click();        
            ispause = false;        
        }
    }
}

function SwitchPlayButton(obj, nextid)
{
    if (ispause)
        return;
    
    var playimg = "PublicImg/rollingbar_pause.jpg";
    var stopimg = "PublicImg/rollingbar_play.jpg";
    var curimg = obj.src.toString().toLowerCase();
    var next = $get(nextid);
    if (curimg.indexOf(playimg.toLowerCase(),0) == -1)
    {
        obj.src = playimg;
        next.click();
    }
    else
        obj.src = stopimg;
}

function PauseSlide(playid)
{
    var play = $get(playid);    
    var stopimg = "PublicImg/rollingbar_play.jpg";
    var curimg = play.src.toString().toLowerCase();
    
    if (curimg.indexOf(stopimg.toLowerCase(),0) == -1)
    {
        play.click();
    }
}

function PlaySlide(playid)
{
    var play = $get(playid);    
    var playimg = "PublicImg/rollingbar_pause.jpg";
    var curimg = play.src.toString().toLowerCase();
    
    if (curimg.indexOf(playimg.toLowerCase(),0) == -1)
    {
        play.click();
    }
}

function showkeylookpopup(id, fromid, fromref) {
    var Divprop = document.getElementById("DivKeyLook");
    var update = false;
    if (Divprop == null) {
        Divprop = document.createElement('div');
        Divprop.style.position = "fixed";
        Divprop.style.borderStyle = "solid";
        Divprop.style.borderWidth = "3px";
        Divprop.style.borderColor = "Gray";
        Divprop.style.zIndex = 10001;
        Divprop.id = "DivKeyLook";
        update = true;
    }
    var keylookurl = "../keylooksrv.aspx?id=" + id;
    if (fromid)
        keylookurl += "&fromid=" + fromid;
    if (fromref)
        keylookurl += "&fromref=" + fromref;
    var content = "<div style=\"position: absolute; top: 0px; right:0px; z-index:2\">";
    content += "<img src=\"../PublicImg/quickLook_close.GIF\" onclick=\"closedivkeylook();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
    content += "</div><div style='width:795px; height:570px;overflow-y: auto; overflow-x: hidden; background-color:#ffffff'>";
    content += "<iframe src=\"" + keylookurl + "\" frameborder=\"0\" scrolling=\"no\" style=\"display:block;width: 100%;height: 100%;\"></iframe></div>";
    Divprop.innerHTML = content;
    if (update) {
        document.body.insertBefore(Divprop, null);

        var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

        var clientWidth;
        var clientHeight;
        switch (Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }

        var xCoord = 0;
        var yCoord = 0;

        var foregroundelementwidth = Divprop.offsetWidth ? Divprop.offsetWidth : Divprop.scrollWidth;
        xCoord = ((clientWidth - foregroundelementwidth) / 2);
        Divprop.style.left = xCoord + 'px';
        var foregroundelementheight = Divprop.offsetHeight ? Divprop.offsetHeight : Divprop.scrollHeight;
        yCoord = ((clientHeight - foregroundelementheight) / 2);
        Divprop.style.top = yCoord + 'px';
    }
}


function closedivkeylook() {
    var divkeylook = document.getElementById("DivKeyLook");    
    if (!divkeylook)
        return;
    document.body.removeChild(divkeylook);
    if (typeof(KeyLookClose) != "undefined")
    {
        KeyLookClose();
    }
}

function AddPackageToShoppingBag(html, tqty, tamnt, type, cnt, freeShippingAmount) { 
    if (typeof(ShowShoppingBag) != "function")    
    {        
        if (typeof(parent.ShowShoppingBag) == "function")
        {
            parent.ShowShoppingBag(html, tqty, tamnt, type, cnt, freeShippingAmount);
            parent.closedivkeylook();
        }
    }
    else {
        ShowShoppingBag(html, tqty, tamnt, type, cnt, freeShippingAmount);
        closedivkeylook();
    }    
}

function ChangeBgc(obj)
{    
    var curclass = obj.className;            
    if (curclass == "itemtempletebg")
        obj.className = "itemtemplete";
    else
        obj.className = "itemtempletebg";
}

function KeyLookPageColor(nid, objid, link, p, c, fo, fref, e, m, curobj)
{
    var obj = $get(objid);
    var name = $get(nid);
    if (obj)
    {                
        obj.onclick = null;
        obj.onclick = function() { showtooltip(p, c, fo, fref, e, m);};
        obj.src = link;
        obj.title = curobj.title;
    }
    if (name)
    {
        name.onclick = null;
        name.onclick = function(){showtooltip(p, c, fo, fref, e, m);};        
    }
}function form1_onkeypress(event) 
{
    if (event == 'undefine' || !event)
        return;
    if (event != null && event.keyCode == 13)
    {
        event.returnValue=false;event.cancel = true;
    }
}
function ShowLoadingDiv()
{    
    var div = document.getElementById('divloading');
    //var x = document.documentElement.clientWidth + document.documentElement.scrollLeft - 50;
    //var y = document.documentElement.clientHeight + document.documentElement.scrollTop - 50;
    //div.style.top = y;
    //div.style.left = x;
    div.style.display = 'block';
    if (typeof (ImageLoader.Init) == "function") {
        ImageLoader.Init();
    }
}
function HideLoadingDiv()
{ 
    var div = document.getElementById('divloading');    
    div.style.display = 'none';    
    if (typeof(initLightbox) == "function")
    {     
        initLightbox();
    }
    if (typeof (ImageLoader.Load) == "function") {
        ImageLoader.Load();
    }
}
function panelkeypress(obj, event)
{
    if (event != null && event.keyCode == 13)
    {        
        var o = document.getElementById(obj);
        if (o)
        {              
            o.click();           
        }
    }
}
function ShowModalPromotion()
{
    var id = "ModalPromotionObj";
    var obj = document.getElementById(id);
    if (!obj)
    {    
        obj = document.createElement('div');
        obj.style.width = "566px";
        obj.style.height = "400px";
        obj.style.margin = "5px 5px 5px 5px";
        obj.style.overflow = "visible";        
        obj.id = id;
        obj.style.backgroundColor = "White";
        obj.style.position = "absolute";
        obj.style.padding = "3px 3px 3px 3px";   
        obj.style.border = "solid 3px Gray";
        obj.style.zIndex = 100002;
        var content = "<div style=\"position: absolute; top: 10px; right:10px; z-index:2\">";
        content += "<img id=\"closebtn\" style=\"visibility:visible;\" src=\"PublicImg/quickLook_close.GIF\" onclick=\"closeModalPromotion();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
        content += "</div>";        
        content += "<div style=\"width:566px; height:400px;\" id=\"divframe\">";
        content += "<iframe id=\"iframe1\" src='QuickLookPage_Keylook.aspx' frameborder=\"0\" scrolling=\"no\" style=\"display:block;visibility:visible;width: 100%;height: 100%;\"></iframe>";
        content += "</div>";        
        obj.innerHTML = content;    
                
        document.body.appendChild(obj);
    }
    var x = 0;
    var y = 0;
    x = document.documentElement.clientWidth / 2 + document.documentElement.scrollLeft - 566 / 2;
    y = document.documentElement.clientHeight / 2 + document.documentElement.scrollTop - 400 / 2;
    obj.style.top = y;
    obj.style.left = x;         
}

function closeModalPromotion()
{
    var id = "ModalPromotionObj";
    var obj = document.getElementById(id);
    if (obj)
    {
        obj.style.visibility = "hidden";
        document.body.removeChild(obj);
    }
}

var adPopup;
var popAd = function() {
    if (adPopup) return;
    adPopup = window.open('http://www.e-giordano.com/WWSInfo.aspx', 'WWSRegister', 'height=168px, width=594px, top=0, left=0, toolbar=no,menubar=no, scrollbars=no, resizable=yes,location=yes,status=no');
    adPopup.blur();
    adPopup.opener.focus();
    document.onclick = null;
}

function ShowWWSMessage() {
    try {
        if (document.onclick == null)
            document.onclick = popAd;
        //popAd();
    } catch (e) {
        //if (document.onclick == null)
        //    document.onclick = popAd;
    }
}

function MM_preloadImages() { //v3.0    
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
        for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    } 
}
function MM_swapImgRestore() { //v3.0    
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_findObj(n, d) { //v4.01    
    var p, i, x; if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length)
    { d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p); }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}var curr = null;   
var ant = null;   
var currtag = null;
var loading = false;

function getTotalSize(element) 
{            
    var size = $common.getSize(element);
    var gutter = { width: 0, height: 0 };
    try {
            var box = $common.getPaddingBox(element);
            gutter.width += box.horizontal;
            gutter.height += box.vertical;
        } catch(ex) { }
        
        try {
            var box = $common.getBorderBox(element);
            gutter.width += box.horizontal;
            gutter.height += box.vertical;
        } catch(ex) { }
        
        var box = $common.getMarginBox(element);
        gutter.width += box.horizontal;
        gutter.height += box.vertical;                        
    size.width += gutter.width;
    size.height += gutter.height;
    return size;
}

function onloading()
{
    loading = true;
}

function grow(b,id,id2)
{
    if(loading) return;    
    var newid = id + "_contnet";
    var newid2 = id + "_sub";
    var menu = document.getElementById(newid);
    var tag = document.getElementById(id2);
   
    if(b)
    {  
        if( id=="000010" || id=="000020" )
            tag.className = "cls"+id+"On1";   
        else
            tag.className = "cls"+id+"On";  
        menu.style.zIndex = 2;
        //tag.className = "cls"+id+"On";
        if( curr != newid )
        {
            var currobj = document.getElementById(curr);
            if( currobj != null )
            {
            currobj.style.height = "0px";
            currobj.style.display = "none";            
            }
            if( ant != null )
            {
                ant.stop();
            }                     
        }        
        if( menu.style.display == "none" )
        {
            menu.style.display = "block";                
            var totalHeight = menu.getAttribute('totalHeight');
            var nheight = 0;
            if( totalHeight == null || totalHeight == '0' )
            {
                var height = menu.getAttribute('itemheight');                
                if( height != null )
                {
                    nheight = parseInt(height);                                      
                }                
                var adDiv = $get(newid2);
                if( adDiv != null )
                {                    
//                    var nb = 0;
//                    var border = adDiv.style.borderTopWidth.toString();
//                    if (border.length > 0)
//                    {
//                        border.replace("px","");
//                        nb = parseInt(border);
//                    }
                    //if (adDiv.style.display != 'none')
                    //    adDiv.style.display = 'block';
                    nheight = nheight + parseInt(adDiv.offsetHeight); //+ nb;
                }
                menu.setAttribute('totalHeight',nheight.toString());
                if( nheight == 0 )
                {
                var size = getTotalSize(menu); 
                height = size.height;
                menu.setAttribute('totalHeight',height.toString());
                nheight = height;
                }
            }
            else
            {
                nheight = parseInt(totalHeight);
            }

            var effects = new Array();
            effects[0] = new Sys.Extended.UI.Animation.LengthAnimation(null, null, null, "style", "height", 0, nheight, "px");
            effects[1] = new Sys.Extended.UI.Animation.FadeInAnimation(null, null, null, .5, 1, false);            
            //var step1 = new AjaxControlToolkit.Animation.ParallelAnimation(menu, null, null, effects)                
            //var step2 = new AjaxControlToolkit.Animation.Action($get(newid2),null,null,'visibility','visible');
            //var step3 = new AjaxControlToolkit.Animation.FadeInAnimation($get(newid2), .5, 20, 0, 1, false);
            //ant =  new AjaxControlToolkit.Animation.SequenceAnimation(menu, null, null, null, 1);
            //ant.add(step1);
            //ant.add(step2);
            //ant.add(step3);
            ant = new Sys.Extended.UI.Animation.ParallelAnimation(menu, .25, 30, effects);
            ant.play();        
            curr = newid;        
            ant.play();        
        }
    }
    else
    {
      tag.className = "cls"+id;
      menu.style.display = "none";    
      menu.style.height = "0px";        
    }
}

function overgrow(b,id,id2)
{
    if(loading) return;
    var newid = id + "_contnet";
    var menu = document.getElementById(newid);
    var tag = document.getElementById(id2);
    if(b)
    {
    if( id=="000010" || id=="000020" )
     tag.className = "cls"+id+"On1";   
    else
     tag.className = "cls"+id+"On";
     
     if( curr != newid )
        {
            var currobj = document.getElementById(curr);
            if( currobj != null )
            {
              currobj.style.height = "0px";
              currobj.style.display = "none";              
            }
            if( ant != null )
            {
                ant.stop();
            }
        }
        
        var totalHeight = menu.getAttribute('totalHeight');           
        
        menu.style.display = "block";
        menu.style.height = totalHeight.toString() + "px";
        curr = newid;
    }
    else
    {
    tag.className = "cls"+id;
    menu.style.display = "none";
    menu.style.height = "0px";
    }
}

var menuant = null;
var _scrollHeight = 0;

function menuslider(imgid, sepid, menuid, tagid)
{
    var img = $get(imgid);
    var sep = $get(sepid);
    var menu = $get(menuid);
    var menucontent = $get(tagid + "_contnet");
    
    var isexpand = img.getAttribute('menuexpand');
    var nheight = 0;
        
    if( _scrollHeight == 0 )
    {
      var size = getTotalSize(menucontent);
      _scrollHeight = size.height; 
    }
    nheight = _scrollHeight;    
    if( nheight == 0 )
    {
        var strheight = menucontent.getAttribute('itemheight');
        if(strheight != null)
        {
            nheight = parseInt(strheight);
        }
    }
    
    if( isexpand == "1" )
    {
        isexpand = "0";        
        img.src='PublicImg/menuimg/open.gif';   
        img.title = '展开菜单栏';             
        if( menuant != null )
        {
            menuant.stop();
        }       
        menuant = null;
        menuant = new Sys.Extended.UI.Animation.LengthAnimation(menucontent, .35, 30, "style", "height", nheight, 0, "px");
        menuant._ended = Function.createDelegate(menuant, CloseFinished);
        menuant.add_ended(menuant._ended);
        menuant._content = menucontent;
        menuant._sep = sep;
        menuant.play();                              
    }
    else
    {
        isexpand = "1";
        img.src='PublicImg/menuimg/close.gif';                
        img.title = '收起菜单栏';
        if( menuant != null )
        {
            menuant.stop();
        }
        menuant = null;
        sep.style.display = "none";        
        menucontent.style.display = 'block';
        menuant = new Sys.Extended.UI.Animation.LengthAnimation(menucontent, .35, 30, "style", "height", 0, nheight, "px");        
        menuant._ended = Function.createDelegate(menuant, OpenFinished);
        menuant.add_ended(menuant._ended);
        menuant.play();         
    }   
    img.setAttribute('menuexpand',isexpand);
    SetCookie('menuexpand',isexpand);     
}

function CloseFinished()
{
    menuant._content.style.display = 'none';
    menuant._sep.style.display = "block"; 
}

function OpenFinished()
{

}

 function SetCookie (name, value) {  
       var expdate = new Date();
       var argv = SetCookie.arguments;
       var argc = SetCookie.arguments.length;
       var expires = (argc > 2) ? argv[2] : null;
       var path = (argc > 3) ? argv[3] : null;
       var domain = (argc > 4) ? argv[4] : null;
       var secure = (argc > 5) ? argv[5] : false;
       if(expires!=null && expires>=0) 
            expdate.setTime(expdate.getTime() + ( expires * 1000 ));
       document.cookie = name + "=" + escape (value) + 
                        ((expires == null || expires < 0) ? ((expires==-1)?"; expires=-1":"") : ("; expires="+ expdate.toGMTString())) +
                        ((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain)) +
                        ((secure == true) ? "; secure" : "");
    }function ImageLoader() { }

ImageLoader._preImages = new Array();
ImageLoader._imgCtl = new Array();
ImageLoader._currentID = 0;
ImageLoader._ImgRef = new Array();
ImageLoader._loaded = new Array();

ImageLoader._timeOut = 300 * 1000;
ImageLoader._timeElapsed = 0;
ImageLoader._checkInterval = 50;
ImageLoader._loadedNum = 0;

ImageLoader.Add = function() {
for (var i = 0; i < arguments.length;ImageLoader._currentID++, i++) {
        if (arguments[i] != null || arguments[i] != "") {
            ImageLoader._ImgRef[ImageLoader._currentID] = arguments[i];
        }
    }
}

ImageLoader.Init = function() {
    ImageLoader._preImages = new Array();
    ImageLoader._imgCtl = new Array();
    ImageLoader._currentID = 0;
    ImageLoader._ImgRef = new Array();
    ImageLoader._loaded = new Array();    
    ImageLoader._timeElapsed = 0;    
    ImageLoader._loadedNum = 0;    
}

ImageLoader.Load = function() {
for (var i = 0; i < ImageLoader._ImgRef.length; i++) {
        var imgctl = document.getElementById(ImageLoader._ImgRef[i]);        
        if (imgctl != null && imgctl.getAttribute('_origurl')) {
            var url = imgctl.getAttribute('_origurl');
            ImageLoader._preImages[i] = new Image();
            ImageLoader._imgCtl[i] = imgctl;
            ImageLoader._loaded[i] = false;            
            ImageLoader._preImages[i].src = url;
        }
    }
    ImageLoader.checkLoad();
}

ImageLoader.checkLoad = function() {
    if (ImageLoader._loadedNum == ImageLoader._preImages.length) {
        //finish        
        return;
    }

    if (ImageLoader._timeElapsed >= ImageLoader._timeOut) {
        //timeout        
        return;
    }

    for (i = 0; i < ImageLoader._preImages.length; i++) {
        if (ImageLoader._loaded[i] == false && ImageLoader._preImages[i].complete) {
            ImageLoader._loaded[i] = true;
            ImageLoader._imgCtl[i].src = ImageLoader._preImages[i].src;
            ImageLoader._imgCtl[i].style.display = 'block';
            ImageLoader._loadedNum++;
        }
    }
    ImageLoader._timeElapsed += ImageLoader._checkInterval;
    setTimeout("ImageLoader.checkLoad()", ImageLoader._checkInterval);
}




function ReportLoader() { }
ReportLoader._currentID = 0;
ReportLoader._DivRef = new Array();
ReportLoader._timeOut = 300 * 1000;
ReportLoader._timeElapsed = 0;
ReportLoader._checkInterval = 50;
ReportLoader._loadedNum = 0;

ReportLoader.Add = function() {
for (var i = 0; i < arguments.length; ReportLoader._currentID++, i++) {
        if (arguments[i] != null || arguments[i] != "") {
            ReportLoader._DivRef[ReportLoader._currentID] = arguments[i];
        }
    }
}

ReportLoader.Init = function() {
    ReportLoader._imgCtl = new Array();
    ReportLoader._currentID = 0;    
    ReportLoader._timeElapsed = 0;
    ReportLoader._loadedNum = 0;
}

ReportLoader.Load = function() {
    for (var i = 0; i < ReportLoader._DivRef.length; i++) {
        var divctr = document.getElementById(ReportLoader._DivRef[i]);
        if (divctr != null && divctr.getAttribute('styl')) {
            var s = divctr.getAttribute('styl');
            var c = divctr.getAttribute('colr');
            var fid = divctr.getAttribute('fobj');
            var fref = divctr.getAttribute('fref');            
            if (WSLog != null) {
                WSLog.GetItemReportInfo(s, c, fid, fref, ReportLoader._DivRef[i], ReportResult);
            }
        }
    }
}

function ReportResult(result) {
    if (result.toString().length > 0) {
        var arr = result.toString().split('@@@');
        var divctr = document.getElementById(arr[0]);
        if (divctr)
            divctr.innerHTML = arr[1].toString();        
    }
    ReportLoader._loadedNum = ReportLoader._loadedNum + 1
}
var qtylabelid;
var compareid;
var startsec;
var endsec;
var machineid;
var customerid;
var ipaddress;
var displayad;
function InitShoppingBag(qtyid, cqtyid, ssec, esec, m,c,ip, showad)
{
    qtylabelid = qtyid;    
    compareid = cqtyid;
    startsec = ssec;
    endsec = esec;
    machineid = m;
    customerid = c;
    ipaddress = ip;
    displayad = showad;
}

function HideShoppingBag()
{
    var div = $find("AVCEShopping").get_element();
    if (div)
    {        
        div.style.visibility = 'hidden';
        var divtotal = document.getElementById("divtotal");
        var divcheckout = document.getElementById("divcheckout");
        divtotal.style.visibility = 'hidden';
        divcheckout.style.visibility = 'hidden';
    }
}

function ShowShoppingBag(html, tqty, tamnt, type, cnt, freeShippingAmount)
{
    var div = $find("AVCEShopping").get_element();    
    if (!div)
        return;    
    div.style.visibility = 'visible';    
    var sAgent = navigator.userAgent.toLowerCase();
    var isFireFox = (sAgent.indexOf("firefox") != -1);    
    if (isFireFox)
        div = window;

    var content = document.getElementById("divitemcontainer");
    var tq = document.getElementById("totalqty");
    var ta = document.getElementById("totalamount");
    var bg = document.getElementById("divshopbg");
    var tp = document.getElementById("spantype");
    var ts = document.getElementById("freeShipping");     
    
    if (!cnt)
        cnt = 1;
    content.innerHTML = html;
             
    var desc = "购物篮";    
    if (type != "buy")
    {
        desc = "对比";
        var divtotal = document.getElementById("divtotal");
        var divcheckout = document.getElementById("divcheckout");
        var divad = document.getElementById("divad");        
        
        divtotal.style.visibility = 'hidden';
        divcheckout.style.visibility = 'hidden';
        divad.style.bottom = "4px";                
        bg.style.height = 71 + 68 * cnt + "px";
        tp.innerHTML = desc;
        if (compareid)
        {        
            var compare = $get(compareid);            
            if (compare)
            {            
                compare.innerHTML = tqty;                
            }
        }
    }
    else
    {
        var divtotal = document.getElementById("divtotal");
        var divcheckout = document.getElementById("divcheckout");
        var divad = document.getElementById("divad");
        divad.style.bottom = "35px";
        if (displayad == "N") {            
            divad.style.visibility = 'hidden';
        }
        divtotal.style.visibility = 'visible';
        divcheckout.style.visibility = 'visible';
        tp.innerHTML = desc;
        bg.style.height = 102 + 68 * cnt + "px";        
        tq.innerHTML = tqty;
        ta.innerHTML = tamnt; 
        ts.innerHTML = freeShippingAmount;
        
            
        if (qtylabelid)
        {        
            var qtylabel = $get(qtylabelid);            
            if (qtylabel)
            {            
                qtylabel.innerHTML = tqty;
            }
        }
    }    
    
    if (document.onclick == null)
        document.onclick = documentClick; 
}

function OverShoppingBag()
{
    document.onclick = null;
}

function OutShoppingBag()
{
    if (document.onclick == null)
        document.onclick = documentClick; 
}

function SetTabActive(cnt, now)
{    
    for (var i = 1;i <= cnt; i++)
    {
        var id = "Li";
        var id2 = "Content";
        id = id + i.toString();
        id2 = id2 + i.toString();
        var obj = document.getElementById(id);
        var divcontent = document.getElementById(id2);        
        if (!obj || !divcontent)
            continue;
        if (i == now)
        {            
            divcontent.style.display = "block";
            obj.className = "divtabactive";
        }
        else
        {
            divcontent.style.display = "none";
            obj.className = "divtabnormal";
        }
    }    
}



function OpenOnlineReception()
{
    var now = new Date();
    var active = true;
    var nowsec = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
    if (startsec < endsec)
    {
        if (nowsec < startsec || nowsec > endsec)
            active = false;
    }
    else
    {
        if (nowsec < startsec && nowsec > endsec)
            active = false;
    }
    if (!active)
    {
        alert("现在并不是客服人员的服务时间，但你可以通过发送电邮到e-shop@e-giordano.com与我们联系，谢谢你的支持");
        return;
    }
    window.open("http://im.e-giordano.com/WCFReception.aspx?m=" + machineid + "&c=" + customerid + "&ip=" + ipaddress, "OnlineReception", "height=584px, width=550px, top=0, left=0, toolbar=no,menubar=no, scrollbars=no, resizable=yes,location=no,status=no");
}function FlowOut(obj)
{    
    obj.style.filter = "alpha(opacity=0)";
    obj.style.MozOpacity = 0;
}
function FlowIn(obj)
{    
    obj.style.filter = "alpha(opacity=10)";    
    obj.style.MozOpacity = 0.1;
}
function MarkPos(obj, divid, fid, fref, tid, tref)
{        
    var div = $get(divid);
    var o = String();    
    var i = obj.href.indexOf('&pos=');
    if (i != -1)
        o = obj.href.substr(0,i);
    else
        o = obj.href;
    obj.href = o + "&pos=" + div.scrollLeft;
    if (fid && fref && tid && tref)
    {
        try
        {
            WSLog.DoLog(fid, fref, tid, tref);
        }
        catch (e)
        {
            ;
        }
    }
}var keylookopen = false;
function ShowKeyLookQuickLook(imgid, divid)
{    
    if (keylookopen)
        return;
    var img = $get(imgid);
    var div = $get(divid);
    
    var lw = img.width;
    var lh = img.height;
    
    if (lw >= 76)
    {
        div.style.top = lh * 2 / 3 + "px";
        div.style.right = (lw - 76) / 3 + "px";   
    }
    else
    {        
        div.style.top = (lh - 25) / 2 + "px";
        div.style.right = (lw - 25) / 2 + "px";
    }        
    div.style.visibility = "visible";
}

function keylookmouseup(obj) {
    var cls = obj.className;
    cls = cls.replace('Over', 'On');
    obj.className = cls;
}

function keylookmouseout(obj) {
    var cls = obj.className;
    cls = cls.replace('On', 'Over');
    obj.className = cls;
}

function keylookmousedown(obj) {
    var cls = obj.className;
    cls = cls.replace('On', 'Down');
    obj.className = cls;
}

function KeyLook_launchQuickLook(keyid,divid)
{
    var div = $get(divid);
    var a = keyid.split('@');
    if (a.length == 3) {
        var id = a[0];
        var fromid = a[1];
        var fromref = a[2];
    }
    else
        return;
    if (typeof(showkeylookpopup) != "undefined") {
        showkeylookpopup(id, fromid, fromref);
        if (div)
        {            
            div.style.visibility = "hidden"; 
            keylookopen = true;                       
        }
    }    
}

function KeyLookClose()
{
    keylookopen = false;
}

function closekeylook(divid,event,width,height)
{
    var x;
    var y;        
    var sAgent = navigator.userAgent.toLowerCase();
    _isFF = (sAgent.indexOf("firefox")!=-1);//firefox
    if (_isFF)
    {
        x = event.layerX;
        y = event.layerY;
    }
    else
    {
	    x = window.event.offsetX;
	    y = window.event.offsetY;
	}
	var div = $get(divid);
    if (x <= 0 || x >= width || y <= 0 || y >= height)
    {
        if (div)    
        {    
            div.style.visibility = "hidden"; 
            keylookopen = false;                             
        }
    }               
}

var IsNextPic = true;

function SwitchPicPosition(imgid, isnext)
{
    IsNextPic = isnext;
    var img = $get(imgid);
    var cururl = img.src.toString();
    var indx = cururl.substr(cururl.length - 5, 1);
    indx = Number(indx);    
    var pre = cururl.substr(0, cururl.length - 5);
    var last = cururl.substr(cururl.length - 4, 4);
    if (isnext)
    {
        indx = indx + 1;        
        if (indx > 9)
            indx = 1;
        cururl = pre + indx.toString() + last;                  
        img.src = cururl;
    }
    else
    {
        indx = indx - 1;
        if (indx < 1)
            indx = 9;
        cururl = pre + indx.toString() + last;
        img.src = cururl;
    }
}

function onErrorHandle(obj) {   
    SwitchPicPosition(obj.id, IsNextPic);    
}/*  Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  THIS FILE IS AUTOMATICALLY GENERATED. When sending patches, please diff
 *  against the source tree, available from the Prototype darcs repository.
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.4.0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}

/*--------------------------------------------------------------------------*/

function $() {
  var elements = new Array();

  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);

    if (arguments.length == 1)
      return element;

    elements.push(element);
  }

  return elements;
}
Object.extend(String.prototype, {
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(eval);
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
  }
});

String.prototype.parseQuery = String.prototype.toQueryParams;

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value >= (result || value))
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (value <= (result || value))
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      iterator(value = collections.pluck(index));
      return value;
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  shift: function() {
    var result = this[0];
    for (var i = 0; i < this.length - 1; i++)
      this[i] = this[i + 1];
    this.length--;
    return result;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type',
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval(this.header('X-JSON'));
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(child);
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element) {
  var Element = new Object();
}

Object.extend(Element, {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      Element[Element.visible(element) ? 'hide' : 'show'](element);
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },

  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node);
    }
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (name in style)
      element.style[name.camelize()] = style[name];
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
  }
});

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        if (this.element.tagName.toLowerCase() == 'tbody') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Field = {
  clear: function() {
    for (var i = 0; i < arguments.length; i++)
      $(arguments[i]).value = '';
  },

  focus: function(element) {
    $(element).focus();
  },

  present: function() {
    for (var i = 0; i < arguments.length; i++)
      if ($(arguments[i]).value == '') return false;
    return true;
  },

  select: function(element) {
    $(element).select();
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
  }
}

/*--------------------------------------------------------------------------*/

var Form = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
  },

  enable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    Field.activate(Form.findFirstElement(form));
  },

  reset: function(form) {
    $(form).reset();
  }
}

Form.Element = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  }
}

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.Serializers.textarea(element);
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value;
      if (!value && !('value' in opt))
        value = opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = new Array();
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected) {
        var optValue = opt.value;
        if (!optValue && !('value' in opt))
          optValue = opt.text;
        value.push(optValue);
      }
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    this._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
    }
  }
});

/* prevent memory leaks in IE */
Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  clone: function(source, target) {
    source = $(source);
    target = $(target);
    target.style.position = 'absolute';
    var offsets = this.cumulativeOffset(source);
    target.style.top    = offsets[1] + 'px';
    target.style.left   = offsets[0] + 'px';
    target.style.width  = source.offsetWidth + 'px';
    target.style.height = source.offsetHeight + 'px';
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      valueT -= element.scrollTop  || 0;
      valueL -= element.scrollLeft || 0;
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// See scriptaculous.js for full license.  

/* ------------- element ext -------------- */  
 
// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';  
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
}

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodes(node) : ''));
  }).flatten().join('');
}

Element.setStyle = function(element, style) {
  element = $(element);
  for(k in style) element.style[k.camelize()] = style[k];
}

Element.setContentZoom = function(element, percent) {  
  Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);  
}

Element.getOpacity = function(element){  
  var opacity;
  if (opacity = Element.getStyle(element, 'opacity'))  
    return parseFloat(opacity);  
  if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))  
    if(opacity[1]) return parseFloat(opacity[1]) / 100;  
  return 1.0;  
}

Element.setOpacity = function(element, value){  
  element= $(element);  
  if (value == 1){
    Element.setStyle(element, { opacity: 
      (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 
      0.999999 : null });
    if(/MSIE/.test(navigator.userAgent))  
      Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});  
  } else {  
    if(value < 0.00001) value = 0;  
    Element.setStyle(element, {opacity: value});
    if(/MSIE/.test(navigator.userAgent))  
     Element.setStyle(element, 
       { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
                 'alpha(opacity='+value*100+')' });  
  }   
}  
 
Element.getInlineOpacity = function(element){  
  return $(element).style.opacity || '';
}  

Element.childrenWithClassName = function(element, className) {  
  return $A($(element).getElementsByTagName('*')).select(
    function(c) { return Element.hasClassName(c, className) });
}

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global') }
    }, arguments[2] || {});
    Effect[Element.visible(element) ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {}

Effect.Transitions.linear = function(pos) {
  return pos;
}
Effect.Transitions.sinoidal = function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse  = function(pos) {
  return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
  return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
}
Effect.Transitions.wobble = function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
  return (Math.floor(pos*10) % 2 == 0 ? 
    (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
  return 0;
}
Effect.Transitions.full = function(pos) {
  return 1;
}

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;
    this.effects.push(effect);
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 40);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.sinoidal,
  duration:   1.0,   // seconds
  fps:        25.0,  // max. 25fps due to Effect.Queue implementation
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn + (this.options.duration*1000);
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  render: function(pos) {
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    // make this work on IE on elements without 'layout'
    if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
      Element.setStyle(this.element, {zoom: 1});
    var options = Object.extend({
      from: Element.getOpacity(this.element) || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    Element.setOpacity(this.element, position);
  }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    Element.makePositioned(this.element);
    this.originalLeft = parseFloat(Element.getStyle(this.element,'left') || '0');
    this.originalTop  = parseFloat(Element.getStyle(this.element,'top')  || '0');
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    Element.setStyle(this.element, {
      left: this.options.x  * position + this.originalLeft + 'px',
      top:  this.options.y  * position + this.originalTop  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element)
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = Element.getStyle(this.element,'position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = Element.getStyle(this.element,'font-size') || '100%';
    ['em','px','%'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      Element.setStyle(this.element, {fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) Element.setStyle(this.element, this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = width + 'px';
    if(this.options.scaleY) d.height = height + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    Element.setStyle(this.element, d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(Element.getStyle(this.element, 'display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {
      backgroundImage: Element.getStyle(this.element, 'background-image') };
    Element.setStyle(this.element, {backgroundImage: 'none'});
    if(!this.options.endcolor)
      this.options.endcolor = Element.getStyle(this.element, 'background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = Element.getStyle(this.element, 'background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    Element.setStyle(this.element,{backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    Element.setStyle(this.element, Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  var oldOpacity = Element.getInlineOpacity(element);
  var options = Object.extend({
  from: Element.getOpacity(element) || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { with(Element) { 
    if(effect.options.to!=0) return;
    hide(effect.element);
    setStyle(effect.element, {opacity: oldOpacity}); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  var options = Object.extend({
  from: (Element.getStyle(element, 'display') == 'none' ? 0.0 : Element.getOpacity(element) || 0.0),
  to:   1.0,
  beforeSetup: function(effect) { with(Element) {
    setOpacity(effect.element, effect.options.from);
    show(effect.element); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { opacity: Element.getInlineOpacity(element), position: Element.getStyle(element, 'position') };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) { with(Element) {
        setStyle(effect.effects[0].element, {position: 'absolute'}); }},
      afterFinishInternal: function(effect) { with(Element) {
         hide(effect.effects[0].element);
         setStyle(effect.effects[0].element, oldStyle); }}
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  Element.makeClipping(element);
  return new Effect.Scale(element, 0, 
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); }} 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var oldHeight = Element.getStyle(element, 'height');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, 
    Object.extend({ scaleContent: false, 
      scaleX: false,
      scaleFrom: 0,
      scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
      restoreAfterFinish: true,
      afterSetup: function(effect) { with(Element) {
        makeClipping(effect.element);
        setStyle(effect.element, {height: '0px'});
        show(effect.element); 
      }},  
      afterFinishInternal: function(effect) { with(Element) {
        undoClipping(effect.element);
        setStyle(effect.element, {height: oldHeight});
      }}
    }, arguments[1] || {})
  );
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = Element.getInlineOpacity(element);
  return new Effect.Appear(element, { 
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { with(Element) {
          [makePositioned,makeClipping].call(effect.element);
        }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide,undoClipping,undoPositioned].call(effect.element);
          setStyle(effect.element, {opacity: oldOpacity});
        }}
      })
    }
  });
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left'),
    opacity: Element.getInlineOpacity(element) };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) { with(Element) {
          makePositioned(effect.effects[0].element); }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide, undoPositioned].call(effect.effects[0].element);
          setStyle(effect.effects[0].element, oldStyle); }} 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left') };
	  return new Effect.Move(element, 
	    { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { with(Element) {
        undoPositioned(effect.element);
        setStyle(effect.element, oldStyle);
  }}}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      setStyle(effect.element, {height: '0px'});
      show(element); }},
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
      undoClipping(effect.element); 
      undoPositioned(effect.element.firstChild);
      undoPositioned(effect.element);
      setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
    }, arguments[1] || {})
  );
}
  
Effect.SlideUp = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  return new Effect.Scale(element, 0, 
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      show(element); }},  
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        undoPositioned(effect.element.firstChild);
        undoPositioned(effect.element);
        setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, 
    { restoreAfterFinish: true,
      beforeSetup: function(effect) { with(Element) {
        makeClipping(effect.element); }},  
      afterFinishInternal: function(effect) { with(Element) {
        hide(effect.element); 
        undoClipping(effect.element); }}
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) { with(Element) {
      hide(effect.element);
      makeClipping(effect.element);
      makePositioned(effect.element);
    }},
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) { with(Element) {
               setStyle(effect.effects[0].element, {height: '0px'});
               show(effect.effects[0].element); }},
             afterFinishInternal: function(effect) { with(Element) {
               [undoClipping, undoPositioned].call(effect.effects[0].element); 
               setStyle(effect.effects[0].element, oldStyle); }}
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) { with(Element) {
           [makePositioned, makeClipping].call(effect.effects[0].element) }},
         afterFinishInternal: function(effect) { with(Element) {
           [hide, undoClipping, undoPositioned].call(effect.effects[0].element);
           setStyle(effect.effects[0].element, oldStyle); }}
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = Element.getInlineOpacity(element);
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 3.0, from: 0,
      afterFinishInternal: function(effect) { Element.setStyle(effect.element, {opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  Element.makeClipping(element);
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        setStyle(effect.element, oldStyle);
      }} });
  }}, arguments[1] || {}));
}
// -----------------------------------------------------------------------------------
//
//	Lightbox v2.03.3
//	by Lokesh Dhakar - http://www.huddletogether.com
//	5/21/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

	Table of Contents
	-----------------
	Configuration
	Global Variables

	Extending Built-in Objects	
	- Object.extend(Element)
	- Array.prototype.removeDuplicates()
	- Array.prototype.empty()

	Lightbox Class Declaration
	- initialize()
	- updateImageList()
	- start()
	- changeImage()
	- resizeImageContainer()
	- showImage()
	- updateDetails()
	- updateNav()
	- enableKeyboardNav()
	- disableKeyboardNav()
	- keyboardAction()
	- preloadNeighborImages()
	- end()
	
	Miscellaneous Functions
	- getPageScroll()
	- getPageSize()
	- getKey()
	- listenKey()
	- showSelectBoxes()
	- hideSelectBoxes()
	- showFlash()
	- hideFlash()
	- pause()
	- initLightbox()
	
	Function Calls
	- addLoadEvent(initLightbox)
	
*/
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var fileLoadingImage = "publicImg/loading1.gif";
var fileBottomNavCloseImage = "publicImg/closelabel.gif";
var fileBottomShareSinaWeiboImage = "http://timg.sjs.sinajs.cn/miniblog2style/images/toolbar/s_org.gif";
var filegoodimg = "publicImg/best_2.gif";
var goodtooltip = "优秀";

var overlayOpacity = 0.8;	// controls transparency of shadow overlay

var animate = true;			// toggles resizing animations
var resizeSpeed = 7;		// controls the speed of the image resizing animations (1=slowest and 10=fastest)

var borderSize = 10;		//if you adjust the padding in the CSS, you will need to update this variable
var imagelab = "图片";
var imagesep = "/";
var PreText = '点击或按"<-"键显示 上一张';
var NextText ='点击或按"->"键显示 下一张';
var CloseText = '点击或按"Esc"键 关闭';
var ShareToSinaWeibo = "分享到新浪微博";
var ShareTitle = "分享这张相片:";
var authTitle = '更多照片'; 

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;  //href, title, lnkto, preViewimg, text, aulnk,selected
var activeImage;

if(animate == true){
	overlayDuration = 0.2;	// shadow fade in/out duration
	if(resizeSpeed > 10){ resizeSpeed = 10;}
	if(resizeSpeed < 1){ resizeSpeed = 1;}
	resizeDuration = (11 - resizeSpeed) * 0.15;
} else { 
	overlayDuration = 0;
	resizeDuration = 0;
}

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	},
	setTitle : function(element,content)
	 {
		element = $(element);
		element.title = content;
	},
	setTarget: function(element, content) {
	    element = $(element);
	    element.setAttribute("target", content);
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
    for(i = 0; i < this.length; i++){
        for(j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {

    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {

        this.updateImageList();

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //	<div id="overlay"></div>
        //	<div id="lightbox">
        //		<div id="outerImageContainer">
        //			<div id="imageContainer">
        //              <a id='lnkimg' href="http://www.e-giordano.com/productphoto/01027570001/phcolr09a2.jpg           //               "title="免烫长袖衬衣">		                
        //				<img id="lightboxImage">
        //              </a>
        //				<div style="" id="hoverNav">
        //					<a href="#" title="上一张" id="prevLink"></a>
        //					<a href="#" title="下一张" id="nextLink"></a>
        //				</div>
        //              <div id='preViewContain' style=" z-index:20;position:absolute;top: 62%;left: 5px; width:145px;  /                        //padding:10px">
        //                    <div id='preViewBox' style="border: 1px solid #ace1f9;
        //                          background-color: #FFF; padding:3px;height:145px">
        //                    <a id='preViewlnk' href="http://www.e-giordano.com/productphoto/01027570001/phcolr09a6.//                              jpg" title="免烫长袖衬衣">
        //                    <img id='preViewImg'  src="http://www.e-giordano.com/productphoto/01027570001///phcolr09a2.jpg"/>
        //                    </a>
        //                  </div>
        //            </div>
        //				<div id="loading">
        //					<a href="#" id="loadingLink">
        //						<img src="images/loading.gif">
        //					</a>
        //				</div>
        //			</div>
        //		</div>
        //		<div id="imageDataContainer">
        //			<div id="imageData">
        //				<div id="imageDetails">
        //                  <div id="dvdetail">
        //					<span id="caption"><a id='caplnk' style="color:#666666" href="#"/></span>
        //					<span id="numberDisplay"><span id='numText'>图片 4 / 7 &nbsp; </span>
        //                    <a id='numlnk' style="color:#666666" >
        //                          免烫长袖衬衣</a></span>
        //                  </div>
        //                  <div id="dvgood">
        //                      <img src="http://localhost/eshop2006/PublicImg/best_1.jpg" />
        //                  </div>
        //				</div>
        //				<div id="bottomNav">
        //					<a href="#" id="bottomNavClose">
        //						<img src="images/close.gif">
        //					</a>
        //				</div>
        //			</div>
        //		</div>
        //	</div>

        var objBody = document.getElementsByTagName("body").item(0);

        var objOverlay = document.createElement("div");
        objOverlay.setAttribute('id', 'overlay');
        objOverlay.style.display = 'none';
        objOverlay.onclick = function() { myLightbox.end(); }
        objBody.appendChild(objOverlay);

        var objLightbox = document.createElement("div");
        objLightbox.setAttribute('id', 'lightbox');
        objLightbox.style.display = 'none';
        objLightbox.onclick = function(e) {	// close Lightbox is user clicks shadow overlay
            if (!e) var e = window.event;
            var clickObj = Event.element(e).id;
            if (clickObj == 'lightbox') {
                myLightbox.end();
            }
        };
        objBody.appendChild(objLightbox);

        var objOuterImageContainer = document.createElement("div");
        objOuterImageContainer.setAttribute('id', 'outerImageContainer');
        objLightbox.appendChild(objOuterImageContainer);

        // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        if (animate) {
            Element.setWidth('outerImageContainer', 250);
            Element.setHeight('outerImageContainer', 250);
        } else {
            Element.setWidth('outerImageContainer', 1);
            Element.setHeight('outerImageContainer', 1);
        }

        var objImageContainer = document.createElement("div");
        objImageContainer.setAttribute('id', 'imageContainer');
        objOuterImageContainer.appendChild(objImageContainer);

        //new
        var objImageLink = document.createElement("a");
        objImageLink.setAttribute('id', 'lnkimg');
        objImageLink.setAttribute('href', '#');
        objImageContainer.appendChild(objImageLink);

        var objLightboxImage = document.createElement("img");
        objLightboxImage.setAttribute('id', 'lightboxImage');
        //objImageContainer.appendChild(objLightboxImage);
        //new
        objImageLink.appendChild(objLightboxImage);

        var objHoverNav = document.createElement("div");
        objHoverNav.setAttribute('id', 'hoverNav');
        objImageContainer.appendChild(objHoverNav);

        var objPrevLink = document.createElement("a");
        objPrevLink.setAttribute('id', 'prevLink');
        objPrevLink.setAttribute('href', '#');
        objHoverNav.appendChild(objPrevLink);

        var objNextLink = document.createElement("a");
        objNextLink.setAttribute('id', 'nextLink');
        objNextLink.setAttribute('href', '#');
        objHoverNav.appendChild(objNextLink);

        //new
        var objpreViewContain = document.createElement("div");
        objpreViewContain.setAttribute('id', 'preViewContain');
        objImageContainer.appendChild(objpreViewContain);

        var objpreViewBox = document.createElement("div");
        objpreViewBox.setAttribute('id', 'preViewBox');
        objpreViewContain.appendChild(objpreViewBox);

        var objpreViewlnk = document.createElement("a");
        objpreViewlnk.setAttribute('id', 'preViewlnk');
        objpreViewlnk.setAttribute('href', '#');
        objpreViewBox.appendChild(objpreViewlnk);

        var objpreViewImg = document.createElement("img");
        objpreViewImg.setAttribute('id', 'preViewImg');
        objpreViewlnk.appendChild(objpreViewImg);

        var objLoading = document.createElement("div");
        objLoading.setAttribute('id', 'loading');
        objImageContainer.appendChild(objLoading);

        var objLoadingLink = document.createElement("a");
        objLoadingLink.setAttribute('id', 'loadingLink');
        objLoadingLink.setAttribute('href', '#');
        objLoadingLink.onclick = function() { myLightbox.end(); return false; }
        objLoading.appendChild(objLoadingLink);

        var objLoadingImage = document.createElement("img");
        objLoadingImage.setAttribute('src', fileLoadingImage);
        objLoadingLink.appendChild(objLoadingImage);

        var objImageDataContainer = document.createElement("div");
        objImageDataContainer.setAttribute('id', 'imageDataContainer');
        objLightbox.appendChild(objImageDataContainer);

        var objImageData = document.createElement("div");
        objImageData.setAttribute('id', 'imageData');
        objImageDataContainer.appendChild(objImageData);

        var objImageDetails = document.createElement("div");
        objImageDetails.setAttribute('id', 'imageDetails');
        objImageData.appendChild(objImageDetails);

        //new
        var objdvdetail = document.createElement("div");
        objdvdetail.setAttribute('id', 'dvdetail');
        objImageDetails.appendChild(objdvdetail);

        var objCaption = document.createElement("span");
        objCaption.setAttribute('id', 'caption');
        objdvdetail.appendChild(objCaption);

        //new
        var objcaplnk = document.createElement("a");
        objcaplnk.setAttribute('id', 'caplnk');
        objcaplnk.setAttribute('href', '#');
        objCaption.appendChild(objcaplnk);

        var objShareTitle = document.createElement("span");
        objShareTitle.setAttribute('id', 'spanShareTitle');
        objShareTitle.setAttribute('class', 'FontCSS');
        objdvdetail.appendChild(objShareTitle);

        var objsinaWeiboBtn = document.createElement("a");
        objsinaWeiboBtn.setAttribute('id', 'lnkbtnSinaWeiBo');
        objdvdetail.appendChild(objsinaWeiboBtn);

        var objsinaWeiboBtnImage = document.createElement("img");
        objsinaWeiboBtnImage.setAttribute('src', fileBottomShareSinaWeiboImage);
        objsinaWeiboBtnImage.setAttribute('title', ShareToSinaWeibo);
        objsinaWeiboBtn.appendChild(objsinaWeiboBtnImage);


        var objNumberDisplay = document.createElement("span");
        objNumberDisplay.setAttribute('id', 'numberDisplay');
        objdvdetail.appendChild(objNumberDisplay);

        //new
        var objnumText = document.createElement("span");
        objnumText.setAttribute('id', 'numText');
        objNumberDisplay.appendChild(objnumText);

        //new
        var objnumlnk = document.createElement("a");
        objnumlnk.setAttribute('id', 'numlnk');
        objnumlnk.setAttribute('href', '#');
        objNumberDisplay.appendChild(objnumlnk);

        //new
        var objdvgood = document.createElement("div");
        objdvgood.setAttribute('id', 'dvgood');
        objImageDetails.appendChild(objdvgood);

        //new 
        var objimgico = document.createElement("img");
        objimgico.setAttribute('id', 'imgico');
        objimgico.setAttribute('src', filegoodimg);
        objimgico.setAttribute('alt', goodtooltip);
        objdvgood.appendChild(objimgico);

        var objBottomNav = document.createElement("div");
        objBottomNav.setAttribute('id', 'bottomNav');
        objImageData.appendChild(objBottomNav);

        var objBottomNavCloseLink = document.createElement("a");
        objBottomNavCloseLink.setAttribute('id', 'bottomNavClose');
        objBottomNavCloseLink.setAttribute('href', '#');
        objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
        objBottomNav.appendChild(objBottomNavCloseLink);

        var objBottomNavCloseImage = document.createElement("img");
        objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
        objBottomNavCloseImage.setAttribute('title', CloseText);
        objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
    },


    //
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateImageList: function() {
        if (!document.getElementsByTagName) { return; }
        var anchors = document.getElementsByTagName('a');
        var areas = document.getElementsByTagName('area');

        // loop through all anchor tags
        for (var i = 0; i < anchors.length; i++) {
            var anchor = anchors[i];

            var relAttribute = String(anchor.getAttribute('rel'));

            // use the string.match() method to catch 'lightbox' references in the rel attribute
            if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))) {
                anchor.onclick = function() { myLightbox.start(this); return false; }
            }
        }

        // loop through all area tags
        // todo: combine anchor & area tag loops
        for (var i = 0; i < areas.length; i++) {
            var area = areas[i];

            var relAttribute = String(area.getAttribute('rel'));

            // use the string.match() method to catch 'lightbox' references in the rel attribute
            if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))) {
                area.onclick = function() { myLightbox.start(this); return false; }
            }
        }
    },


    //
    //	start()
    //	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {

        hideSelectBoxes();
        hideFlash();
        // stretch overlay to fill page and fade in
        var arrayPageSize = getPageSize();
        Element.setWidth('overlay', arrayPageSize[0]);
        Element.setHeight('overlay', arrayPageSize[1]);

        new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });

        imageArray = [];
        imageNum = 0;

        if (!document.getElementsByTagName) { return; }
        var anchors = document.getElementsByTagName(imageLink.tagName);

        // if image is NOT part of a set..
        if ((imageLink.getAttribute('rel') == 'lightbox')) {
            // add single image to imageArray
            imageArray.push(new Array(imageLink.getAttribute('href'),
			                          imageLink.getAttribute('title'),
			                          imageLink.getAttribute('lnkto'),
			                          imageLink.getAttribute('preViewimg'),
			                          imageLink.getAttribute('text'),
			                          imageLink.getAttribute('aulnk'),
			                          imageLink.getAttribute('selected'),
			                          imageLink.getAttribute("fromid"),
		                              imageLink.getAttribute("imgid"),
		                              imageLink.getAttribute("toid"),
		                              imageLink.getAttribute("isql")
                                      ));
        } else {
            // if image is part of a set..

            // loop through anchors, find other images in set, and add them to imageArray
            for (var i = 0; i < anchors.length; i++) {
                var anchor = anchors[i];
                if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))) {
                    imageArray.push(new Array(anchor.getAttribute('href'),
					                          anchor.getAttribute('title'),
					                          anchor.getAttribute('lnkto'),
			                                  anchor.getAttribute('preViewimg'),
			                                  anchor.getAttribute('text'),
			                                  anchor.getAttribute('aulnk'),
			                                  anchor.getAttribute('selected'),
			                                  anchor.getAttribute('fromid'),
			                                  anchor.getAttribute('imgid'),
			                                  anchor.getAttribute('toid'),
			                                  anchor.getAttribute('isql')
			                                   ));
                }
            }
            imageArray.removeDuplicates();
            while (imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++; }
        }

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = getPageScroll();
        var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
        var lightboxLeft = arrayPageScroll[0];
        Element.setTop('lightbox', lightboxTop);
        Element.setLeft('lightbox', lightboxLeft);

        Element.show('lightbox');

        this.changeImage(imageNum);
    },

    //
    //	changeImage()
    //	Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function(imageNum) {

        activeImage = imageNum; // update global var

        // hide elements during transition
        if (animate) { Element.show('loading'); }
        //Element.hide('lnkimg');
        Element.hide('lightboxImage');

        Element.hide('hoverNav');
        Element.hide('prevLink');
        Element.hide('nextLink');

        Element.hide('preViewContain');
        Element.hide('preViewBox');
        Element.hide('preViewlnk');
        Element.hide('preViewImg');

        Element.hide('imageDataContainer');
        Element.hide('numberDisplay');
        Element.hide('dvgood');

        imgPreloader = new Image();

        // once image is preloaded, resize image container
        imgPreloader.onload = function() {
            Element.setSrc('lightboxImage', imageArray[activeImage][0]);
            myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);

            imgPreloader.onload = function() { }; //	clear onLoad, IE behaves irratically with animated gifs otherwise 
        }
        imgPreloader.src = imageArray[activeImage][0];
    },

    //
    //	resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get curren width and height
        this.widthCurrent = Element.getWidth('outerImageContainer');
        this.heightCurrent = Element.getHeight('outerImageContainer');

        // get new width and height
        var widthNew = (imgWidth + (borderSize * 2));
        var heightNew = (imgHeight + (borderSize * 2));
        if (widthNew < 659 && heightNew > 400)
            widthNew = 659;

        // scalars based on change from old to new
        this.xScale = (widthNew / this.widthCurrent) * 100;
        this.yScale = (heightNew / this.heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        wDiff = this.widthCurrent - widthNew;
        hDiff = this.heightCurrent - heightNew;

        if (!(hDiff == 0)) { new Effect.Scale('outerImageContainer', this.yScale, { scaleX: false, duration: resizeDuration, queue: 'front' }); }
        if (!(wDiff == 0)) { new Effect.Scale('outerImageContainer', this.xScale, { scaleY: false, delay: resizeDuration, duration: resizeDuration }); }

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        if ((hDiff == 0) && (wDiff == 0)) {
            if (navigator.appVersion.indexOf("MSIE") != -1) { pause(250); } else { pause(100); }
        }

        Element.setHeight('prevLink', imgHeight);
        Element.setHeight('nextLink', imgHeight);
        Element.setWidth('imageDataContainer', widthNew);

        this.showImage();
    },

    //
    //	showImage()
    //	Display image and begin preloading neighbors.
    //
    showImage: function() {
        Element.hide('loading');
        //Element.show('lnkimg');		
        if (imageArray[activeImage][2]) {
            Element.setHref('lnkimg', imageArray[activeImage][2]);
        }
        if (imageArray[activeImage][4]) {
            Element.setTitle('lnkimg', imageArray[activeImage][4]);
        }
        if (imageArray[activeImage][7] && imageArray[activeImage][8] && imageArray[activeImage][9]) {
            var from = imageArray[activeImage][7];
            var imgid = imageArray[activeImage][8];
            var to = imageArray[activeImage][9];
            WSStyleTopic.LogPhotoView(imgid, from, to);
        }
        new Effect.Appear('lightboxImage', { duration: resizeDuration, queue: 'end', afterFinish: function() { myLightbox.updateDetails(); } });
        this.preloadNeighborImages();
    },

    //
    //	updateDetails()
    //	Display caption, image number, and bottom nav.
    //
    updateDetails: function() {

        if (imageArray[activeImage][3]) {
            Element.setSrc('preViewImg', imageArray[activeImage][3]);
            Element.show('preViewContain');
            Element.show('preViewBox');
            Element.show('preViewlnk');
            Element.show('preViewImg');
        }
        if (imageArray[activeImage][2]) {
            Element.setHref('preViewlnk', imageArray[activeImage][2]);
            if (imageArray[activeImage][10])
                Element.setTarget('lnkimg', '_blank');
        }
        if (imageArray[activeImage][6]) {
            if (imageArray[activeImage][6] == 'Y')
                Element.show('dvgood');
            else
                Element.hide('dvgood');
        }
        else {
            Element.hide('dvgood');
        }

        // if caption is not null
        if (imageArray[activeImage][1]) {
            Element.show('caption');
            Element.show('caplnk');
            Element.setInnerHTML('caplnk', imageArray[activeImage][1]);
            Element.show('spanShareTitle');
            Element.setInnerHTML('spanShareTitle', ShareTitle);

            //"javascript:weibo('" + SharePhotoUrl + "','" + ShareText + "','" + ShareUrl + "','1372160682',screen, document, encodeURIComponent);";
            var weiboJs = "javascript:weibo('" + imageArray[activeImage][3] + "','" + imageArray[activeImage][1] + "','http://www.e-giordano.com/" + imageArray[activeImage][5] + "','1372160682',screen, document, encodeURIComponent);";
            Element.setHref('lnkbtnSinaWeiBo', weiboJs);
            
            if (imageArray[activeImage][5]) {
                Element.setHref('caplnk', imageArray[activeImage][5]);
                Element.setTitle('caplnk', authTitle);
                if (imageArray[activeImage][10])
                    Element.setTarget('caplnk', "_Blank");
            }
            //Element.setInnerHTML( 'caption', imageArray[activeImage][1]);

        }

        // if image is part of set display 'Image x of x' 
        if (imageArray.length > 1) {
            Element.show('numberDisplay');
            Element.show('numText');
            Element.show('numlnk');
            //Element.setInnerHTML( 'numberDisplay', "Image " + eval(activeImage + 1) + " of " + imageArray.length);
            //Element.setInnerHTML( 'numberDisplay', imagelab + " " + eval(activeImage + 1) + " " + imagesep + " " + imageArray.length);
            Element.setInnerHTML('numText', imagelab + " " + eval(activeImage + 1) + " " + imagesep + " " + imageArray.length + "  ");
            if (imageArray[activeImage][4]) {
                Element.setInnerHTML('numlnk', imageArray[activeImage][4]);
            }
            if (imageArray[activeImage][2]) {
                Element.setHref('numlnk', imageArray[activeImage][2]);
            }
        }

        new Effect.Parallel(
			[new Effect.SlideDown('imageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }),
			  new Effect.Appear('imageDataContainer', { sync: true, duration: resizeDuration })],
			{ duration: resizeDuration, afterFinish: function() {
			    // update overlay size and update nav
			    var arrayPageSize = getPageSize();
			    Element.setHeight('overlay', arrayPageSize[1]);
			    myLightbox.updateNav();
			}
			}
		);
    },

    //
    //	updateNav()
    //	Display appropriate previous and next hover navigation.
    //
    updateNav: function() {

        Element.show('hoverNav');

        // if not first image in set, display prev image button
        if (activeImage != 0) {
            Element.show('prevLink');
            Element.setTitle('prevLink', PreText);
            document.getElementById('prevLink').onclick = function() {
                myLightbox.changeImage(activeImage - 1); return false;
            }
        }

        // if not last image in set, display next image button
        if (activeImage != (imageArray.length - 1)) {
            Element.show('nextLink');
            Element.setTitle('nextLink', NextText);
            document.getElementById('nextLink').onclick = function() {
                myLightbox.changeImage(activeImage + 1); return false;
            }
        }

        this.enableKeyboardNav();
    },

    //
    //	enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.onkeydown = this.keyboardAction;
    },

    //
    //	disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.onkeydown = '';
    },

    //
    //	keyboardAction()
    //
    keyboardAction: function(e) {
        if (e == null) { // ie
            keycode = event.keyCode;
            escapeKey = 27;
        } else { // mozilla
            keycode = e.keyCode;
            escapeKey = e.DOM_VK_ESCAPE;
        }

        key = String.fromCharCode(keycode).toLowerCase();

        if ((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)) {	// close lightbox
            myLightbox.end();
        } else if ((key == 'p') || (keycode == 37)) {	// display previous image
            if (activeImage != 0) {
                myLightbox.disableKeyboardNav();
                myLightbox.changeImage(activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)) {	// display next image
            if (activeImage != (imageArray.length - 1)) {
                myLightbox.disableKeyboardNav();
                myLightbox.changeImage(activeImage + 1);
            }
        }

    },

    //
    //	preloadNeighborImages()
    //	Preload previous and next images.
    //
    preloadNeighborImages: function() {

        if ((imageArray.length - 1) > activeImage) {
            preloadNextImage = new Image();
            preloadNextImage.src = imageArray[activeImage + 1][0];
        }
        if (activeImage > 0) {
            preloadPrevImage = new Image();
            preloadPrevImage.src = imageArray[activeImage - 1][0];
        }

    },

    //
    //	end()
    //
    end: function() {
        this.disableKeyboardNav();
        Element.hide('lightbox');
        new Effect.Fade('overlay', { duration: overlayDuration });
        showSelectBoxes();
        showFlash();
    }
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	
// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}


// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Help from Ran Bar-On [ran2103@gmail.com]
//

function pause(ms){
	var date = new Date();
	curDate = null;
	do{var curDate = new Date();}
	while( curDate - date < ms);
}
/*
function pause(numberMillis) {
	var curently = new Date().getTime() + sender;
	while (new Date().getTime();	
}
*/
// ---------------------------------------------------



function initLightbox() { myLightbox = new Lightbox(); }
Event.observe(window, 'load', initLightbox, false);

// JScript File

// -----------------------------------------------------------------------------------
//
//	Lightbox v2.03.3
//	by Lokesh Dhakar - http://www.huddletogether.com
//	5/21/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*

	Table of Contents
	-----------------
	Configuration
	Global Variables

	Extending Built-in Objects	
	- Object.extend(Element)
	- Array.prototype.removeDuplicates()
	- Array.prototype.empty()

	Lightbox Class Declaration
	- initialize()
	- updateImageList()
	- start()
	- changeImage()
	- resizeImageContainer()
	- showImage()
	- updateDetails()
	- updateNav()
	- enableKeyboardNav()
	- disableKeyboardNav()
	- keyboardAction()
	- preloadNeighborImages()
	- end()
	
	Miscellaneous Functions
	- getPageScroll()
	- getPageSize()
	- getKey()
	- listenKey()
	- showSelectBoxes()
	- hideSelectBoxes()
	- showFlash()
	- hideFlash()
	- pause()
	- initLightbox()
	
	Function Calls
	- addLoadEvent(initLightbox)
	
*/
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var fileLoadingImage = "publicImg/loading1.gif";		
var fileBottomNavCloseImage = "publicImg/closelabel.gif";
var filegoodimg = "publicImg/best_2.gif";
var goodtooltip = "优秀";

var overlayOpacity2 = 0.8;	// controls transparency of shadow overlay
var animate2 = true;			// toggles resizing animations
var resizeSpeed2 = 7;		// controls the speed of the image resizing animations (1=slowest and 10=fastest)
var init = false;

var borderSize = 10;		//if you adjust the padding in the CSS, you will need to update this variable
var imagelab = "图片";
var imagesep = "/";
var PreText = '点击或按"<-"键显示 上一张';
var NextText ='点击或按"->"键显示 下一张';
var CloseText = '点击或按"Esc"键 关闭';
var authTitle = '更多照片'; 

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray2 = new Array;  //href, title, lnkto, preViewimg, text, aulnk,selected
var activeImage2;

if(animate2 == true){
	overlayDuration2 = 0.2;	// shadow fade in/out duration
	if(resizeSpeed2 > 10){ resizeSpeed2 = 10;}
	if(resizeSpeed2 < 1){ resizeSpeed2 = 1;}
	resizeDuration2 = (11 - resizeSpeed2) * 0.15;
} else { 
	overlayDuration2 = 0;
	resizeDuration2 = 0;
}

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src; 
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	},
	setTitle : function(element,content)
	 {
		element = $(element);
		element.title = content;
	},
	setHidden: function(element){
	    element = $(element);
	    element.style.visibility = "hidden";
	    },
	setVisible: function(element){
	    element = $(element);
	    element.style.visibility = "visible";
	    }
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
    for(i = 0; i < this.length; i++){
        for(j = this.length-1; j>i; j--){        
            if(this[i][0] == this[j][0]){
                this.splice(j,1);
            }
        }
    }
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

//
//	Lightbox Class Declaration
//	- initialize()
//	- start()
//	- changeImage()
//	- resizeImageContainer()
//	- showImage()
//	- updateDetails()
//	- updateNav()
//	- enableKeyboardNav()
//	- disableKeyboardNav()
//	- keyboardNavAction()
//	- preloadNeighborImages()
//	- end()
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox2 = Class.create();

Lightbox2.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateImageList and then
	// the function inserts html at the bottom of the page which is used to display the shadow 
	// overlay and the image container.
	//
	initialize: function() {	
		
		this.updateImageList();

		// Code inserts html at the bottom of the page that looks similar to this:
		//
		//	<div id="overlay2"></div>
		//	<div id="lightbox2">
		//		<div id="outerImageContainer2">
		//			<div id="imageContainer2">  
		//             <div id="lightboxImage2" />
		//			   <div id="loading2">
		//					<a href="#" id="loadingLink2">
		//						<img src="images/loading.gif">
		//					</a>
		//				</div>
		//			</div>
		//		</div>
		//		<div id="imageDataContainer2">		
		//		</div>
		//	</div>
        initdom();        			
	},


	//
	// updateImageList()
	// Loops through anchor tags looking for 'lightbox' references and applies onclick
	// events to appropriate links. You can rerun after dynamically adding images w/ajax.
	//
	updateImageList: function() {	
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');
		//var areas = document.getElementsByTagName('area');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('googlemapbox'))){
				anchor.onclick = function () {myLightbox2.start(this); return false;}
			}
		}

		// loop through all area tags
		// todo: combine anchor & area tag loops
	//	for (var i=0; i< areas.length; i++){
	//		var area = areas[i];
			
	//		var relAttribute = String(area.getAttribute('rel'));
			
	//		// use the string.match() method to catch 'lightbox' references in the rel attribute
	//		if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox2'))){
	//			area.onclick = function () {myLightbox2.start(this); return false;}
	//		}
	//	}
	},
	
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {	
		hideSelectBoxes();
		hideFlash();
        
        if(!init)
        {
            initdom();
        }
        
		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setWidth('overlay2', arrayPageSize[0]);
		Element.setHeight('overlay2', arrayPageSize[1]);

		new Effect.Appear('overlay2', { duration: overlayDuration2, from: 0.0, to: overlayOpacity2 });

		imageArray2 = [];
		imageNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName( imageLink.tagName);

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'googlemapbox')){
			// add single image to imageArray
			imageArray2.push(new Array(imageLink.getAttribute('href'), 
			                          imageLink.getAttribute('title'),
			                          imageLink.getAttribute('lnkto'),			                          
			                          imageLink.getAttribute('preViewimg'),
			                          imageLink.getAttribute('text'),
			                          imageLink.getAttribute('aulnk'),
			                          imageLink.getAttribute('selected') ));			
		} 
		//else {
		//// if image is part of a set..

		//	// loop through anchors, find other images in set, and add them to imageArray
		//	for (var i=0; i<anchors.length; i++){
		//		var anchor = anchors[i];
		//		if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
		//			imageArray2.push(new Array(anchor.getAttribute('href'), 
		//			                          anchor.getAttribute('title'),
		//			                          anchor.getAttribute('lnkto'),			                          
		//	                                  anchor.getAttribute('preViewimg'),
		//	                                  anchor.getAttribute('text'),
		//	                                  anchor.getAttribute('aulnk'),
		//	                                  anchor.getAttribute('selected') ));
		//		}
		//	}
		//	imageArray2.removeDuplicates();
		//	while(imageArray2[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		//}

		// calculate top and left offset for the lightbox 
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
		var lightboxLeft = arrayPageScroll[0];
		Element.setTop('lightbox2', lightboxTop);
		Element.setLeft('lightbox2', lightboxLeft);
		
		Element.setVisible('lightbox2');
		//Element.show('lightbox2');
		
		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	// Load data
	changeImage: function(imageNum) {	
		
		activeImage2 = imageNum;	// update global var

		// hide elements during transition
		if(animate2){ Element.show('loading2');}		
		Element.hide('lightboxImage2');														
		Element.hide('imageDataContainer2');		
		
	    if( !imageArray2[activeImage2][1]  )
	    {
	        myLightbox2.end();
	        return;
	    }
	    
	    AJAXLoad(imageArray2[activeImage2][1]);													
	},
	
	BindData : function(result){	    
	    var tel, html;	    	    
	    var longitude, latitude, address,path;
	    var arr = result.split("@@@");
	    var uselt = false;	    
	    if (arr.length >= 4)
	    {	        
	        uselt = true;
	        tel = arr[0];
	        longitude = arr[1];
	        latitude = arr[2];
	        address = arr[3];
	        path = arr[4];
	    }
	    else
	    {
	        tel = arr[0];
	        address = arr[1];   
	    }               	    			
	    myLightbox2.resizeImageContainer(640, 520);
	    var objlightboxImage2 = $('lightboxImage2');	        
	    if (uselt)
	    {		               
	        loadmaplt(objlightboxImage2, longitude, latitude, address, path, tel);
	    }
	    else
	    {      	        
            loadmap(address,'lightboxImage2');
	    }	    	
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get curren width and height
		this.widthCurrent = Element.getWidth('outerImageContainer2');
		this.heightCurrent = Element.getHeight('outerImageContainer2');

		// get new width and height
		var widthNew = (imgWidth  + (borderSize * 2));
		var heightNew = (imgHeight  + (borderSize * 2));

		// scalars based on change from old to new
		this.xScale = ( widthNew / this.widthCurrent) * 100;
		this.yScale = ( heightNew / this.heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = this.widthCurrent - widthNew;
		hDiff = this.heightCurrent - heightNew;

        Element.setWidth( 'outerImageContainer2', widthNew);
        Element.setHeight('outerImageContainer2', heightNew);
        
		//if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer2', this.yScale, {scaleX: false, duration: resizeDuration2, queue: 'front'}); }
		//if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer2', this.xScale, {scaleY: false, delay: resizeDuration2, duration: resizeDuration2}); }

		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		//if((hDiff == 0) && (wDiff == 0)){
		//	if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
		//}

		//Element.setHeight('prevLink', imgHeight);
		//Element.setHeight('nextLink', imgHeight);
		//Element.setWidth( 'imageDataContainer2', widthNew);

		this.showImage();
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		Element.hide('loading2');	
		Element.show('lightboxImage2');				
		//Element.show('outerImageContainer2');	
		new Effect.Appear('outerImageContainer2', { duration: resizeDuration2, queue: 'end', afterFinish: function(){ ; } });
		//new Effect.Appear('lightboxImage2', { duration: resizeDuration2, queue: 'end', afterFinish: function(){	myLightbox2.updateDetails(); } });
		//this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {
	    	   
		new Effect.Parallel(
			[ new Effect.SlideDown( 'imageDataContainer2', { sync: true, duration: resizeDuration2, from: 0.0, to: 1.0 }), 
			  new Effect.Appear('imageDataContainer2', { sync: true, duration: resizeDuration2 }) ], 
			{ duration: resizeDuration2, afterFinish: function() {
				// update overlay size and update nav
				//var arrayPageSize = getPageSize();
				//Element.setHeight('overlay', arrayPageSize[1]);
				//myLightbox.updateNav();
				this.enableKeyboardNav();
				}
			} 
		);
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		Element.show('hoverNav');				

		// if not first image in set, display prev image button
		if(activeImage != 0){
			Element.show('prevLink');
			Element.setTitle('prevLink',PreText);
			document.getElementById('prevLink').onclick = function() {
				myLightbox.changeImage(activeImage - 1); return false;
			}
		}

		// if not last image in set, display next image button
		if(activeImage != (imageArray2.length - 1)){
			Element.show('nextLink');
			Element.setTitle('nextLink',NextText);
			document.getElementById('nextLink').onclick = function() {
				myLightbox.changeImage(activeImage + 1); return false;
			}
		}
		
		this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
			escapeKey = 27;
		} else { // mozilla
			keycode = e.keyCode;
			escapeKey = e.DOM_VK_ESCAPE;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey))
		{	// close lightbox
			myLightbox.end();
		}
	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray2.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray2[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray2[activeImage - 1][0];
		}
	
	},

	//
	//	end()
	//
	end: function() {
	        this.disableKeyboardNav();		
	        Element.setHidden('lightbox2');	        
	        new Effect.Fade('overlay2', { duration: overlayDuration2});	        
	        showSelectBoxes();
	        showFlash();
	}
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	
// ---------------------------------------------------

function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

//---------------------------------------------------
function initdom()
{
    var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay2');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myLightbox2.end(); }
		objBody.appendChild(objOverlay);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox2');		
		//objLightbox.style.display = 'none';
		objLightbox.style.visibility = "hidden";
		objLightbox.onclick = function(e) {	// close Lightbox is user clicks shadow overlay
			if (!e) var e = window.event;
			var clickObj = Event.element(e).id;
			if ( clickObj == 'lightbox2') {
				myLightbox2.end();
			}
		};
		objBody.appendChild(objLightbox);
			
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer2');
		objLightbox.appendChild(objOuterImageContainer);

		// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
		// If animations are turned off, it will be hidden as to prevent a flicker of a
		// white 250 by 250 box.
		if(animate2){
			Element.setWidth('outerImageContainer2', 250);
			Element.setHeight('outerImageContainer2', 250);			
		} else {
			Element.setWidth('outerImageContainer2', 1);
			Element.setHeight('outerImageContainer2', 1);			
		}

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer2');
		objOuterImageContainer.appendChild(objImageContainer);	   	    	    
	
	    var objLightboxImage = document.createElement("div");
		objLightboxImage.setAttribute('id','lightboxImage2');
		objLightboxImage.style.display = 'none';		
		objImageContainer.appendChild(objLightboxImage);
		Element.setWidth('lightboxImage2', 640);
	    Element.setHeight('lightboxImage2', 500);
	
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','loading2');
		objImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','loadingLink2');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { myLightbox2.end(); return false; }
		objLoading.appendChild(objLoadingLink);
	
		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileLoadingImage);
		objLoadingLink.appendChild(objLoadingImage);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','imageDataContainer2');
		objLightbox.appendChild(objImageDataContainer);	
		init = true;
}

function AJAXLoad(arge)
{    
    WSShopMap.GetShopMapScript(arge,AJAXResult);
}

function AJAXResult(result)
{
    myLightbox2.BindData(result);
}

// ---------------------------------------------------

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}


// ---------------------------------------------------

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}


//---------------------------------------------------
//google map api
//---------------------------------------------------
var map;
var geocoder;
function loadmaplt(obj, longitude, latitude, address, path, tel)
{   
    var latlng = new google.maps.LatLng(latitude, longitude);
    var myOptions = {
        zoom: 18,
        center: latlng,
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(obj, myOptions);    
    
    var contentString = '';
    
    if (path.length == 0)    
        contentString = '<div style="width:160px;height:60px;"><span style="display:block">' + address + 'tel:(' + tel + ')</span></div>';
    else
        contentString = '<div style="width:165px;height:155px;"><img src="' + path + '"/><span style="display:block">' + address + 'tel:(' + tel + ')</span></div>';
    
    var infowindow = new google.maps.InfoWindow({
    content: contentString
    });

    var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: address});
    infowindow.open(map,marker);
    //google.maps.event.addListener(marker, 'click', function() {;});  
}

function loadmap(initaddress, id)
{      
    var obj = document.getElementById(id);
    var latlng = new google.maps.LatLng(39.917, 116.397);
    var myOptions = {
        zoom: 18,
        center: latlng,
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(obj, myOptions);

    geocoder = new google.maps.Geocoder();
    if (geocoder) 
    {
        geocoder.geocode( { 'address': initaddress}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) 
        {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
            });
            var infowindow = new google.maps.InfoWindow({
                    content: address
                    });
            infowindow.open(map,marker);
        }         
        });
    }      
}

function pause(ms){
	var date = new Date();
	curDate = null;
	do{var curDate = new Date();}
	while( curDate - date < ms);
}


function initLightbox2() { myLightbox2 = new Lightbox2(); }
Event.observe(window, 'load', initLightbox2, false);

var imgurl;
var orgalt;
var color;
var divvisible;
function PreviewImg(url, id, lnkid, divid, obj)
{    
    var img = document.getElementById(id);     
    var lnk = document.getElementById(lnkid);
    var div = document.getElementById(divid);    
    imgurl = img.src;
    img.src = url;    
    var alt = obj.getAttribute("alt");                    
    if (div)
    {
        if (alt != null && alt.length > 0)
        {
            if (div.style.visibility == "hidden")
            {
                divvisible = false;
                div.style.visibility = "visible"
                lnk.innerHTML = alt;
            }
            else
            {
                divvisible = true;
                orgalt = lnk.innerHTML;
                lnk.innerHTML = alt;
            }
        }
        else
        {
            if (div.style.visibility == "visible")
            {
                divvisible = true;
                div.style.visibility = "hidden";
            }
        }
    }
}
function RecoverImg(id, lnkid, divid)
{
    var img = document.getElementById(id);
    var lnk = document.getElementById(lnkid);
    var div = document.getElementById(divid);
    if (imgurl != null)    
        img.src = imgurl;        
    if (div)    
    {
        if (divvisible)
        {
            div.style.visibility = "visible"
            if (orgalt != null)
                lnk.innerHTML = orgalt;
        }
        else
        {
            div.style.visibility = "hidden";
            if (orgalt != null)
                lnk.innerHTML = orgalt;
        }
    }
}

function ShowModalSizeChart(id)
{    
    var modal = $find(id);
    modal.show();
}

function CheckTogetherPrice(obj,curpric, curfinl, keypric, keyfinl, totalid, finalid, saveid, lnkid, stylid)
{
    var totalobj = document.getElementById(totalid);
    var finalobj = document.getElementById(finalid);
    var saveobj = document.getElementById(saveid);
    var totalpric = Number(totalobj.innerHTML);
    var finalpric = Number(finalobj.innerHTML); 
        
    //totalpric = totalpric + finalpric;           
        
    if (obj.checked)
    {
        if (finalpric == totalpric && curpric != curfinl)
            finalpric = totalpric - keypric + keyfinl;
        totalpric += curpric;
        finalpric += curfinl;
    }
    else
    {        
        totalpric -= curpric;
        finalpric -= curfinl;
    }
        
    if (Math.ceil(totalpric - finalpric) == Math.ceil(keypric - keyfinl))
        finalpric = totalpric;
    
    var balance = totalpric - finalpric;
    saveobj.innerHTML = balance.toFixed(2);
    totalobj.innerHTML = totalpric.toFixed(2);
    finalobj.innerHTML = finalpric.toFixed(2);    
    
    try
    {
        var lnkobj = document.getElementById(lnkid);
        var url = lnkobj.href;
        var i = url.indexOf('&sel='); 
        var j = url.substr(0, i);        
                        
        if (obj.checked)
        {            
            if (i == -1)
                url += "&sel=" + stylid;
            else 
            {
                if (j.length == url.length - 5)
                    url += stylid;
                else
                    url += "@" + stylid;
            }
        }
        else
        {
            url = url.replace("@" + stylid, '')
            url = url.replace(stylid, '');            
        }        
        lnkobj.href = url;
    }
    catch (e)
    {
        
    }
}
function InitItem(containerid, panelid, ih, iw, d, css, startpos)
{        
    var container = document.getElementById(containerid);
    var panel = document.getElementById(panelid);
    panel.style.width = panel.scrollWidth + "px";    
    container.style.height = ih;
    container.style.width = iw;                     
    if (css != '')
        container.className = css;
    container.insertBefore(panel, null);
    if (d == 0)    
    {                
        container.style.overflowX = 'hidden';        
        container.scrollLeft = startpos;
        if (!document.all)                 
            container.style.overflowY = 'hidden';
        else                    
            container.style.overflowY = 'visible';        
    }
    else
    {        
        container.style.overflowY = 'hidden';   
        container.scrollTop = startpos;    
        if (!document.all)
            container.style.overflowX = 'hidden';
        else                    
            container.style.overflowX = 'visible';        
    }
}

function InitContain(id, h, w, innercss)
{
    var con = document.getElementById(id);
    con.style.height = h;
    con.style.width = w;
    if (innercss != '')
        con.className = innercss;       
}

var slide_lmt = 15;
var slide_cnt = 0;
var slide_time;
var slide_cnt2 = 0;
var slide_time2;
function SlideItem(container, event)
{        
    var itemwidth = container.getAttribute("itemwidth");
    var d = container.getAttribute("direction");    
    SlideItem1(container,itemwidth, d, event);
}

function SlideItem1(container, itemwidth, d, event)
{                    
    var pos;
    var sAgent = navigator.userAgent.toLowerCase();    
    var QuickLook_isFF = (sAgent.indexOf("firefox")!=-1);//firefox    
    if (QuickLook_isFF)
    {
        if (d == 0)
            pos = event.layerX;
        else
            pos = event.layerY;
    }
    else
    {        
	    if (d == 0)
            pos = window.event.offsetX;
        else
            pos = window.event.offsetY;
        var obj = window.event.srcElement;        
        var p = obj.parentElement;        
        while (p != null && p.id != container.id)
        {                        
            if (d == 0)
            {   
                if (p.tagName.toLocaleUpperCase() == "SPAN")
                    pos += p.offsetLeft;
            }
            else
            {        
                if (p.tagName.toLocaleUpperCase() == "SPAN")        
                    pos += p.offsetTop;
            }            
            p = p.parentElement;            
        }                
	}

    if (d == 0)
    {
        var cw = container.clientWidth / 2;              
        var cp = container.scrollLeft;        
        if (pos - cp < cw)        
            cp = Number(cp) - Number(itemwidth);                    
        else if (pos - cp > cw)       
            cp = Number(cp) + Number(itemwidth);        
        //container.scrollLeft = cp;
        var step = (cp - container.scrollLeft) / slide_lmt;
        step = Math.ceil(step);
        if (slide_time2 != null)
        {
            clearTimeout(slide_time2);
            slide_time2 = null;
            slide_cnt2 = 0;
        }
        cscrollLeft(container.id, step);
    }
    else
    {        
        var cw = container.clientHeight / 2;        
        var cp = container.scrollTop;                        
        if (pos - cp < cw)        
            cp = Number(cp) - Number(itemwidth);                    
        else if (pos - cp > cw)       
            cp = Number(cp) + Number(itemwidth);                
        //container.scrollTop = cp;
        var step = (cp - container.scrollTop) / slide_lmt;
        step = Math.ceil(step);
        if (slide_time != null)
        {
            clearTimeout(slide_time);
            slide_time = null;
            slide_cnt = 0;
        }
        cscrollTop(container.id, step);                
    }
}
function cscrollTop(conid, step)
{        
    var con = document.getElementById(conid);
    con.scrollTop = con.scrollTop + Number(step);
    if (slide_cnt < slide_lmt)
    {
        slide_cnt++;        
        slide_time = setTimeout("cscrollTop('" + conid + "','" + step + "')",50);
    }
    else
    {
        slide_cnt = 0;
        clearTimeout(slide_time);
        slide_time = null;
    }
}

function cscrollLeft(conid, step)
{
    var con = document.getElementById(conid);
    //alert(con.scrollLeft);
    con.scrollLeft = con.scrollLeft + Number(step);
    if (slide_cnt2 < slide_lmt)
    {        
        slide_cnt2++;        
        slide_time2 = setTimeout("cscrollLeft('" + conid + "','" + step + "')",50);
    }
    else
    {
        slide_cnt2 = 0;
        clearTimeout(slide_time2);
        slide_time2 = null;
    }
}

var slide_divpanel;
var slide_iTimer1;
var slide_iTimer2;
var slide_pos = 0;

function continuescrollleft(id)
{        
    slide_divpanel = document.getElementById(id);    
    clearTimeout(slide_iTimer2);    
    slide_pos = slide_divpanel.scrollLeft;
    slide_pos=slide_pos-10;        
    if (slide_pos < 0)
    {
        clearTimeout(slide_iTimer1);
        slide_pos = 0;
    }
    else
    {
        slide_divpanel.scrollLeft = slide_pos;
        slide_iTimer1 = setTimeout("continuescrollleft('" + id + "')", 100);
    }    
}

function continuescrollright(id)
{
    slide_divpanel = document.getElementById(id);    
    clearTimeout(slide_iTimer1);
    slide_pos = slide_divpanel.scrollLeft;
    slide_pos=slide_pos+10;        
    if (slide_pos > slide_divpanel.scrollWidth - slide_divpanel.clientWidth)
    {
        clearTimeout(slide_iTimer2);
        slide_pos = slide_divpanel.clientWidth;
    }
    else
    {
        slide_divpanel.scrollLeft = slide_pos;
        slide_iTimer2 = setTimeout("continuescrollright('" + id + "')", 100);
    }
}
function stopscroll1()
{             
    clearTimeout(slide_iTimer2);
    clearTimeout(slide_iTimer1);   
}

var divpanel;
var isFF;
var iTimer1;
var iTimer2;
var pos = 0;

function continuescrollup(id)
{
    divpanel = document.getElementById(id);    
    clearTimeout(iTimer2);    
    pos = divpanel.scrollTop;
    pos=pos-10;        
    if (pos < 0)
    {
        clearTimeout(iTimer1);
        pos = 0;
    }
    else
    {
        divpanel.scrollTop = pos;
        iTimer1 = setTimeout("continuescrollup('" + id + "')", 100);
    }    
}
function continuescrolldown(id)
{
    divpanel = document.getElementById(id)    
    clearTimeout(iTimer1);    
    pos = divpanel.scrollTop;
    pos=pos+10;        
    if (pos > divpanel.scrollHeight - divpanel.clientHeight)
    {
        clearTimeout(iTimer2);
        pos = divpanel.clientHeight;
    }
    else
    {
        divpanel.scrollTop = pos;
        iTimer2 = setTimeout("continuescrolldown('" + id + "')", 100);
    }    
}
function stopscroll()
{         
    clearTimeout(iTimer2);
    clearTimeout(iTimer1);       
}

function SetAutoPlay(id, d, ap, event)
{        
    if (ap.toString().toUpperCase() == "TRUE")
    {           
        if (d == 0)
        {
            autoscrollright(id);
        }
        else 
        {
            autoscrolldown(id);
        }          
    }
}

function StopAutoPlay()
{
    if (slide_iTimer2 != null)
        clearTimeout(slide_iTimer2);
    if (iTimer2 != null)
        clearTimeout(iTimer2);  
}

function autoscrollright(id)
{
    var panel = document.getElementById(id);    
    //alert(panel.scrollWidth - panel.clientWidth);
    clearTimeout(slide_iTimer1);
    slide_pos = panel.scrollLeft;
    slide_pos=slide_pos+10;
        
    if (slide_pos > panel.scrollWidth - panel.clientWidth)
    {                
        slide_pos = 0;
    }    
    panel.scrollLeft = slide_pos;
    slide_iTimer2 = setTimeout("autoscrollright('" + id + "')", 100);    
}
function autoscrolldown(id)
{
    var panel = document.getElementById(id)    
    clearTimeout(iTimer1);    
    pos = panel.scrollTop;
    pos=pos+10;        
    if (pos > panel.scrollHeight - panel.clientHeight)
    {        
        pos = 0;
    }    
    panel.scrollTop = pos;
    iTimer2 = setTimeout("autoscrolldown('" + id + "')", 100);        
}// JScript File
var ZoomImage_ImageHeight = 313;
var ZoomImage_ImageWidth = 250;
var ZoomImage_iDivHeight = 250;
var ZoomImage_iDivWidth = 250;
var ZoomImage_iDragHeight;
var ZoomImage_iDragWidth;
var ZoomImage_iMultiple;
var ZoomImage_iPrevImgWidth = 800;
var ZoomImage_iPrevImgHeight = 1000;
var ZoomImage_imageurl = '';
var ZoomImage_bigimageurl = '';
var ZoomImage_nedref = false;
var ZoomImage_img;
var ZoomImage_Pic_bg;
var ZoomImage_Drag_Box;
var ZoomImage_Prev_Win;
var ZoomImage_isFF = false;
function ZoomImage_ShowPicBG(img,bgid,dragid,previd,imgheight,imgwidth,divheight,divwidth,prevheight,prevwidth,event)
{    
    var sAgent = navigator.userAgent.toLowerCase();    
    ZoomImage_isFF = (sAgent.indexOf("firefox")!=-1);
    
    ZoomImage_img = img;
    ZoomImage_Pic_bg = bgid; 
    ZoomImage_Drag_Box = dragid;    
    ZoomImage_Prev_Win = previd;
    ZoomImage_ImageHeight = imgheight;
    ZoomImage_ImageWidth = imgwidth;
    ZoomImage_iDivHeight = divheight;
    ZoomImage_iDivWidth = divwidth;
    ZoomImage_iPrevImgWidth = prevwidth;
    ZoomImage_iPrevImgHeight = prevheight;
    if (ZoomImage_Pic_bg.style.visibility != "visible")
    {         
        ZoomImage_Pic_bg.style.width = ZoomImage_ImageWidth + "px";
        ZoomImage_Pic_bg.style.height = ZoomImage_ImageHeight + "px";
    }
    ZoomImage_Pic_bg.style.visibility = "visible";
    ZoomImage_Drag_Box.style.visibility = "visible";
    ZoomImage_Prev_Win.style.visibility = "visible";
        
    if(ZoomImage_imageurl != ZoomImage_img.src)
    {
        ZoomImage_nedref = true;
        ZoomImage_imageurl = ZoomImage_img.src;          
//        if (ZoomImage_isFF) 
//            ZoomImage_bigimageurl = ZoomImage_imageurl.replace("4.jpg","6.jpg");        
//        else
            ZoomImage_bigimageurl = ZoomImage_img.getAttribute("bigimg");                            
    }        
    ZoomImage_DragImg(ZoomImage_Pic_bg,event,ZoomImage_nedref);         
}
String.prototype.trim = function()
{
var reExtraSpace = /^\s*(.*?)\s+$/;
return this.replace(reExtraSpace,"$1");
}

function ZoomImage_DragImg(src,event,refs)
{                               		
	var iPosX, iPosY;
	var idragX, idragY;	
	var sAgent = navigator.userAgent.toLowerCase();    
    ZoomImage_isFF = (sAgent.indexOf("firefox")!=-1);//firefox  
    var iMouseX;
    var iMouseY;
    if (ZoomImage_isFF)
    {
        iMouseX = event.layerX;
        iMouseY = event.layerY;
    }
    else
    {
	    iMouseX = window.event.offsetX;
	    iMouseY = window.event.offsetY;		
	}
	ZoomImage_iMultiple = ZoomImage_iPrevImgWidth / ZoomImage_ImageWidth;
	ZoomImage_iDragHeight = ZoomImage_iDivHeight / ZoomImage_iMultiple;
	ZoomImage_iDragWidth = ZoomImage_iDivWidth / ZoomImage_iMultiple;
	if (iMouseX <= (ZoomImage_iDragWidth /2))
	{
	    idragX = 0;
	}
	else
	{
	    if ((ZoomImage_ImageWidth - iMouseX) <= (ZoomImage_iDragWidth / 2))
	        idragX = -(ZoomImage_ImageWidth - ZoomImage_iDragWidth);
	    else
	        idragX = -(iMouseX - ZoomImage_iDragWidth / 2);
	}
	
	if (iMouseY <= (ZoomImage_iDragHeight /2))
	{
	    idragY = 0;
	}
	else
	{
	    if ((ZoomImage_ImageHeight - iMouseY) <= (ZoomImage_iDragHeight / 2))
	        idragY = -(ZoomImage_ImageHeight - ZoomImage_iDragHeight);
	    else
	        idragY = -(iMouseY - ZoomImage_iDragHeight / 2);
	}
	iPosY = idragY * ZoomImage_iMultiple;
	iPosX = idragX * ZoomImage_iMultiple;
	
	if (ZoomImage_iPrevImgHeight + iPosY < ZoomImage_iDivHeight)
	    iPosY = ZoomImage_iDivHeight - ZoomImage_iPrevImgHeight;
	if (ZoomImage_iPrevImgWidth + iPosX < ZoomImage_iDivWidth)
	    iPosX = ZoomImage_iDivWidth - ZoomImage_iPrevImgWidth;
	
	var top;
	if (iMouseY - ZoomImage_iDragHeight / 2 <= 0)
	    top = 0;
	else if (ZoomImage_ImageHeight - iMouseY <= ZoomImage_iDragHeight / 2)
	    top = ZoomImage_ImageHeight - ZoomImage_iDragHeight;
	else
	    top = iMouseY - ZoomImage_iDragHeight / 2;
	    	
	var left;
	if (iMouseX - ZoomImage_iDragWidth / 2 <= 0)
	    left = 0;
	else if (ZoomImage_ImageWidth - iMouseX <= ZoomImage_iDragWidth / 2)
	    left = ZoomImage_ImageWidth - ZoomImage_iDragWidth;
	else
	    left = iMouseX - ZoomImage_iDragWidth / 2;	   	
	
	ZoomImage_Drag_Box.style.top = top + "px";
	ZoomImage_Drag_Box.style.left = left + "px";		
	
	if (ZoomImage_Drag_Box.innerHTML.toString().trim() == "" || refs)
	{	    
	    ZoomImage_Drag_Box.style.width = ZoomImage_iDragWidth + "px";
	    ZoomImage_Drag_Box.style.height = ZoomImage_iDragHeight + "px";
		ZoomImage_Drag_Box.innerHTML = "<img id='BigImg" + ZoomImage_img.id + "' style='position:absolute'>";		
		BigImg = document.getElementById("BigImg" + ZoomImage_img.id);
		BigImg.src = ZoomImage_imageurl;
		BigImg.style.height = ZoomImage_ImageHeight + "px";
		BigImg.style.width = ZoomImage_ImageWidth + "px";
		ZoomImage_nedref = false;
	}
	else
	    BigImg = document.getElementById("BigImg" + ZoomImage_img.id);	           	        
    
	if (refs || ZoomImage_Prev_Win.innerHTML.toString().trim() == "")
	{	    	    
	    ZoomImage_Prev_Win.style.width = ZoomImage_iDivWidth + "px";
	    ZoomImage_Prev_Win.style.height = ZoomImage_iDivHeight + "px";	    	    	    
	    if (ZoomImage_ImageHeight >= 313)
	        ZoomImage_Prev_Win.style.top = String(ZoomImage_ImageHeight - ZoomImage_iDivHeight) + "px";
	    else
	        ZoomImage_Prev_Win.style.top = String((ZoomImage_ImageHeight - ZoomImage_iDivHeight) / 2) + "px";	    
	    ZoomImage_Prev_Win.style.left = String(ZoomImage_ImageWidth) + "px";	    	    	    	    
	    ZoomImage_Prev_Win.innerHTML = "<img id='PrevImg" + ZoomImage_img.id + "' style='position:absolute;'/>";
	    PrevImg = document.getElementById("PrevImg" + ZoomImage_img.id);	    
	    PrevImg.src = ZoomImage_bigimageurl;	    
	    PrevImg.style.width = ZoomImage_iPrevImgWidth + "px";
	    PrevImg.style.height = ZoomImage_iPrevImgHeight + "px";
	    ZoomImage_nedref = false;
	}		
	else
	    PrevImg = document.getElementById("PrevImg" + ZoomImage_img.id);	
		    	    		    
	BigImg.style.top = idragY + "px";
    BigImg.style.left = idragX + "px";
	PrevImg.style.top = iPosY + "px";
	PrevImg.style.left = iPosX + "px";	
}
function ZoomImage_HidePicBG(event)
{        
    var x;
    var y;
    if (ZoomImage_isFF)
    {
        x = event.layerX;
        y = event.layerY;
    }
    else
    {
	    x = window.event.offsetX;
	    y = window.event.offsetY;
	}        	
    if (x <= 0 || x >= ZoomImage_ImageWidth || y <= 0 || y >= ZoomImage_ImageHeight)
    {
        ZoomImage_Pic_bg.style.visibility = "hidden";        
        ZoomImage_Drag_Box.style.visibility = "hidden";        
        ZoomImage_Prev_Win.style.visibility = "hidden";        
    }
}

function ZoomImage_Setimg(img, bg, drag, prev, event, divlength, prevh, prevw)
{        
    ZoomImage_ShowPicBG(img, bg, drag, prev, img.height,img.width,divlength, divlength, prevh, prevw, event);
}

function ZoomImage_DragBox(bg, event)
{
    //var bg = document.getElementById(bgid)
    ZoomImage_DragImg(bg,event);
}
if (typeof deconcept == "undefined") { var deconcept = new Object(); }
if (typeof deconcept.util == "undefined") { deconcept.util = new Object(); }
if (typeof deconcept.SWFObjectUtil == "undefined") { deconcept.SWFObjectUtil = new Object(); }
deconcept.SWFObject = function(_1, id, w, h, _5, c, _7, _8, _9, _a, _b) {
    if (!document.createElement || !document.getElementById) { return; }
    this.DETECT_KEY = _b ? _b : "detectflash";
    this.skipDetect = true;
    this.params = new Object();
    this.variables = new Object();
    this.attributes = new Array();
    if (_1) { this.setAttribute("swf", _1); }
    if (id) { this.setAttribute("id", id); }
    if (w) { this.setAttribute("width", w); }
    if (h) { this.setAttribute("height", h); }
    if (_5) { this.setAttribute("version", new deconcept.PlayerVersion(_5.toString().split("."))); }
    this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"), _7);
    if (c) { this.addParam("bgcolor", c); } else { this.addParam("wmode", "transparent"); }
    var q = _8 ? _8 : "high";
    this.addParam("quality", q);
    this.setAttribute("useExpressInstall", _7);
    this.setAttribute("doExpressInstall", false);
    var _d = (_9) ? _9 : window.location;
    this.setAttribute("xiRedirectUrl", _d);
    this.setAttribute("redirectUrl", "");
    if (_a) { this.setAttribute("redirectUrl", _a); } 
};
deconcept.SWFObject.prototype = { setAttribute: function(_e, _f) {
    this.attributes[_e] = _f;
}, getAttribute: function(_10) {
    return this.attributes[_10];
}, addParam: function(_11, _12) {
    this.params[_11] = _12;
}, getParams: function() {
    return this.params;
}, addVariable: function(_13, _14) {
    this.variables[_13] = _14;
}, getVariable: function(_15) {
    return this.variables[_15];
}, getVariables: function() {
    return this.variables;
}, getVariablePairs: function() {
    var _16 = new Array();
    var key;
    var _18 = this.getVariables();
    for (key in _18) {
        _16.push(key + "=" + _18[key]);
    }
    return _16;
}, getSWFHTML: function() {
    var _19 = "";
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
        if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
        _19 = "<embed type=\"application/x-shockwave-flash\" src=\"" + this.getAttribute("swf") + "\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\"";
        _19 += " id=\"" + this.getAttribute("id") + "\" name=\"" + this.getAttribute("id") + "\" ";
        var _1a = this.getParams();
        for (var key in _1a) { _19 += [key] + "=\"" + _1a[key] + "\" "; }
        var _1c = this.getVariablePairs().join("&");
        if (_1c.length > 0) { _19 += "flashvars=\"" + _1c + "\""; }
        _19 += " pluginspage=\"http://www.macromedia.com/go/getflashplayer\"/>";
    } else {
        if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
        _19 = "<object id=\"" + this.getAttribute("id") + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\">";
        _19 += "<param name=\"movie\" value=\"" + this.getAttribute("swf") + "\" />";
        var _1d = this.getParams();
        for (var key in _1d) { _19 += "<param name=\"" + key + "\" value=\"" + _1d[key] + "\" />"; }
        var _1f = this.getVariablePairs().join("&");
        if (_1f.length > 0) { _19 += "<param name=\"flashvars\" value=\"" + _1f + "\" />"; }
        _19 += "</object>";
    }
    return _19;
}, write: function(_20) {
    if (this.getAttribute("useExpressInstall")) {
        var _21 = new deconcept.PlayerVersion([6, 0, 65]);
        if (this.installedVer.versionIsValid(_21) && !this.installedVer.versionIsValid(this.getAttribute("version"))) {
            this.setAttribute("doExpressInstall", true);
            this.addVariable("MMredirectURL", escape(this.getAttribute("xiRedirectUrl")));
            document.title = document.title.slice(0, 47) + " - Flash Player Installation";
            this.addVariable("MMdoctitle", document.title);
        }
    }
    if (this.skipDetect || this.getAttribute("doExpressInstall") || this.installedVer.versionIsValid(this.getAttribute("version"))) {
        var n = (typeof _20 == "string") ? document.getElementById(_20) : _20;
        n.innerHTML = this.getSWFHTML();        
        return true;
    } else {
        if (this.getAttribute("redirectUrl") != "") { document.location.replace(this.getAttribute("redirectUrl")); }
    }
    return false;
}
};
deconcept.SWFObjectUtil.getPlayerVersion = function(_23, _24) {
    var _25 = new deconcept.PlayerVersion([0, 0, 0]);
    if (navigator.plugins && navigator.mimeTypes.length) {
        var x = navigator.plugins["Shockwave Flash"];
        if (x && x.description) { _25 = new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".")); }
    } else {
        try {
            var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            for (var i = 15; i > 6; i--) {
                try {
                    axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
                    _25 = new deconcept.PlayerVersion([i, 0, 0]);
                    break;
                }
                catch (e) { } 
            } 
        }
        catch (e) { }
        if (_23 && _25.major > _23.major) { return _25; }
        if (!_23 || ((_23.minor != 0 || _23.rev != 0) && _25.major == _23.major) || _25.major != 6 || _24) {
            try { _25 = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(",")); }
            catch (e) { } 
        } 
    }
    return _25;
};
deconcept.PlayerVersion = function(_29) {
    this.major = parseInt(_29[0]) != null ? parseInt(_29[0]) : 0;
    this.minor = parseInt(_29[1]) || 0;
    this.rev = parseInt(_29[2]) || 0;
};
deconcept.PlayerVersion.prototype.versionIsValid = function(fv) {
    if (this.major < fv.major) { return false; }
    if (this.major > fv.major) { return true; }
    if (this.minor < fv.minor) { return false; }
    if (this.minor > fv.minor) { return true; }
    if (this.rev < fv.rev) { return false; } return true;
};
deconcept.util = { getRequestParameter: function(_2b) {
    var q = document.location.search || document.location.hash;
    if (q) {
        var _2d = q.indexOf(_2b + "=");
        var _2e = (q.indexOf("&", _2d) > -1) ? q.indexOf("&", _2d) : q.length;
        if (q.length > 1 && _2d > -1) {
            return q.substring(q.indexOf("=", _2d) + 1, _2e);
        } 
    } return "";
} 
};
if (Array.prototype.push == null) {
    Array.prototype.push = function(_2f) {
        this[this.length] = _2f;
        return this.length;
    };
}

function playFlash(url, vid, playerid, downloadid, width, height) {
    var obj = document.getElementById(playerid);
    var vobj = document.getElementById(vid);

    var getQueryParamValue = deconcept.util.getRequestParameter;
    var FlashObject = deconcept.SWFObject; // for backwards compatibility
    var SWFObject = deconcept.SWFObject;
    if (SWFObject) {
        var fo = new SWFObject("PublicImg/player.swf", "movie_" + playerid, "100%", "100%", 7, "#FFFFFF");
        fo.addParam("allowFullScreen", "false");
        fo.addParam("allowscriptaccess", "always");
        fo.addParam("menu", false);
        fo.addVariable("file", url);
        //fo.addParam("wmode", "opaque");
        fo.addVariable("autostart", true);
        fo.addVariable("controlbar", "none");
        fo.addVariable("repeat", "always");
        fo.addVariable("icons", false);
        fo.addVariable("bufferlength", 3);
        fo.addVariable("stretching", "fill");
        fo.addVariable("screencolor", "white");
        if (!fo.write(playerid)) {
            document.getElementById(downloadid).style.height = "20px";
            document.getElementById(downloadid).innerHTML = "您需要升级FLASH播放器";
        }
        obj.style.height = height;
        obj.style.width = width;
        vobj.style.height = height;
        vobj.style.width = width;
        window.focus();
    }
}

function playVideo(url, imgid, vid, playerid, downloadid, SLhostid, width, height, btnobj) {    
     
    var obj = document.getElementById(playerid);
    var imgobj = document.getElementById(imgid);
    var vobj = document.getElementById(vid);
    var slhost = document.getElementById(SLhostid);
    if (btnobj.className == "ProductBtnPlayVideo")
        btnobj.className = "ProductBtnBackPic";
    else
        btnobj.className = "ProductBtnPlayVideo";
    
    if (obj.innerHTML.toString().length > 10) {
        obj.innerHTML = "";
        if (imgobj)
            imgobj.style.display = "block";
        vobj.style.height = "0px";
        obj.style.height = "0px";
        return;
    }

    if (Silverlight.isInstalled("3.0")) {
        var sl1 = document.getElementById("sl1");
        if (vobj.style.height != "0px") {
            if (imgobj)
                imgobj.style.display = "block";
            vobj.style.height = "0px";
            slhost.style.height = "0px";
            sl1.style.height = "0px";
            return;
        }
        url = url.replace('.flv', '.wmv');
        if (imgobj)
            imgobj.style.display = "none";
        vobj.style.height = height;
        slhost.style.height = height;
        sl1.style.height = height;
        try {
            var player = sl1.content.Player;
            player.Play(url);
            return;
        }
        catch (e) {
            url = url.replace('.wmv', '.flv');
            vobj.style.height = "0px";
            slhost.style.height = "0px";
            sl1.style.height = "0px";
        }
    }
        
    var getQueryParamValue = deconcept.util.getRequestParameter;
    var FlashObject = deconcept.SWFObject; // for backwards compatibility
    var SWFObject = deconcept.SWFObject;        
    if (SWFObject) {
        var fo = new SWFObject("PublicImg/player.swf", "movie_" + playerid, "100%", "100%", 7, "#FFFFFF");
        fo.addParam("allowFullScreen", "false");
        fo.addParam("allowscriptaccess", "always");
        fo.addParam("menu", false);
        fo.addVariable("file", url);
        //fo.addParam("wmode", "opaque");
        fo.addVariable("autostart", true);
        fo.addVariable("controlbar", "none");
        fo.addVariable("repeat", "always");
        fo.addVariable("icons", false);        
        fo.addVariable("bufferlength", 3);
        fo.addVariable("stretching", "fill");
        fo.addVariable("screencolor", "white");
        if (!fo.write(playerid)) {
            document.getElementById(downloadid).style.height = "20px";
            document.getElementById(downloadid).innerHTML = "您需要升级FLASH播放器";
        }
        if (imgobj)
            imgobj.style.display = "none";
        obj.style.height = height;
        vobj.style.height = height;
        window.focus();
    }
}

function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }

    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    if (errorType == "ImageError" || errorType == "MediaError") {
        return;
    }

    var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    //throw new Error(errMsg);
}      
///////////////////////////////////////////////////////////////////////////////
//
//  Silverlight.js   			version 2
//
//  This file is provided by Microsoft as a helper file for websites that
//  incorporate Silverlight Objects. This file is provided under the Silverlight 
//  SDK 2 license available at http://go.microsoft.com/fwlink/?linkid=108846.  
//  You may not use or distribute this file or the code in this file except as 
//  expressly permitted under that license.
// 
//  Copyright (c) 2007 Microsoft Corporation. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////

if(!window.Silverlight)window.Silverlight={};Silverlight._silverlightCount=0;Silverlight.ua=null;Silverlight.available=false;Silverlight.fwlinkRoot="http://go.microsoft.com/fwlink/?LinkID=";Silverlight.detectUserAgent=function(){var a=window.navigator.userAgent;Silverlight.ua={OS:"Unsupported",Browser:"Unsupported"};if(a.indexOf("Windows NT")>=0)Silverlight.ua.OS="Windows";else if(a.indexOf("PPC Mac OS X")>=0)Silverlight.ua.OS="MacPPC";else if(a.indexOf("Intel Mac OS X")>=0)Silverlight.ua.OS="MacIntel";if(Silverlight.ua.OS!="Unsupported")if(a.indexOf("MSIE")>=0){if(navigator.userAgent.indexOf("Win64")==-1)if(parseInt(a.split("MSIE")[1])>=6)Silverlight.ua.Browser="MSIE"}else if(a.indexOf("Firefox")>=0){var b=a.split("Firefox/")[1].split("."),c=parseInt(b[0]);if(c>=2)Silverlight.ua.Browser="Firefox";else{var d=parseInt(b[1]);if(c==1&&d>=5)Silverlight.ua.Browser="Firefox"}}else if(a.indexOf("Safari")>=0)Silverlight.ua.Browser="Safari"};Silverlight.detectUserAgent();Silverlight.isInstalled=function(d){var c=false,a=null;try{var b=null;if(Silverlight.ua.Browser=="MSIE")b=new ActiveXObject("AgControl.AgControl");else if(navigator.plugins["Silverlight Plug-In"]){a=document.createElement("div");document.body.appendChild(a);if(Silverlight.ua.Browser=="Safari")a.innerHTML='<embed type="application/x-silverlight-2-b1" />';else a.innerHTML='<object type="application/x-silverlight-2-b1"  data="data:application/x-silverlight-2-b1," />';b=a.childNodes[0]}document.body.innerHTML;if(b.IsVersionSupported(d))c=true;b=null;Silverlight.available=true}catch(e){c=false}if(a)document.body.removeChild(a);return c};Silverlight.createObject=function(l,g,m,j,k,i,h){var b={},a=j,c=k;a.source=l;b.parentElement=g;b.id=Silverlight.HtmlAttributeEncode(m);b.width=Silverlight.HtmlAttributeEncode(a.width);b.height=Silverlight.HtmlAttributeEncode(a.height);b.ignoreBrowserVer=Boolean(a.ignoreBrowserVer);b.inplaceInstallPrompt=false;b.onGetSilverlightClick=Silverlight.HtmlAttributeEncode(c.onGetSilverlightClick);var e=a.version.split(".");b.shortVer=e[0]+"."+e[1];b.version=a.version;a.initParams=i;a.windowless=a.isWindowless;a.maxFramerate=a.framerate;for(var d in c)if(c[d]&&d!="onLoad"&&d!="onError"){a[d]=c[d];c[d]=null}delete a.width;delete a.height;delete a.id;delete a.onLoad;delete a.onError;delete a.ignoreBrowserVer;delete a.inplaceInstallPrompt;delete a.version;delete a.isWindowless;delete a.framerate;delete a.data;delete a.src;delete c.onGetSilverlightClick;if(Silverlight.isInstalled(b.version)){if(Silverlight._silverlightCount==0)if(window.addEventListener)window.addEventListener("onunload",Silverlight.__cleanup,false);else window.attachEvent("onunload",Silverlight.__cleanup);var f=Silverlight._silverlightCount++;a.onLoad="__slLoad"+f;a.onError="__slError"+f;window[a.onLoad]=function(a){if(c.onLoad)c.onLoad(document.getElementById(b.id),h,a)};window[a.onError]=function(a,b){if(c.onError)c.onError(a,b);else Silverlight.default_error_handler(a,b)};slPluginHTML=Silverlight.buildHTML(b,a)}else slPluginHTML=Silverlight.buildPromptHTML(b);if(b.parentElement)b.parentElement.innerHTML=slPluginHTML;else return slPluginHTML};Silverlight.supportedUserAgent=function(){var a=Silverlight.ua,b=a.OS=="Unsupported"||a.Browser=="Unsupported"||a.OS=="Windows"&&a.Browser=="Safari"||a.OS.indexOf("Mac")>=0&&a.Browser=="IE";return !b};Silverlight.buildHTML=function(c,d){var a=[],e,i,g,f,h;if(Silverlight.ua.Browser=="Safari"){a.push("<embed ");e="";i=" ";g='="';f='"';h=' type="application/x-silverlight-2-b1"/>'+"<iframe style='visibility:hidden;height:0;width:0'/>"}else{a.push('<object type="application/x-silverlight-2-b1" data="data:application/x-silverlight-2-b1,"');e=">";i=' <param name="';g='" value="';f='" />';h="</object>"}a.push(' id="'+c.id+'" width="'+c.width+'" height="'+c.height+'" '+e);for(var b in d)if(d[b])a.push(i+Silverlight.HtmlAttributeEncode(b)+g+Silverlight.HtmlAttributeEncode(d[b])+f);a.push(h);return a.join("")};Silverlight.default_error_handler=function(e,b){var d,c=b.ErrorType;d=b.ErrorCode;var a="\nSilverlight error message     \n";a+="ErrorCode: "+d+"\n";a+="ErrorType: "+c+"       \n";a+="Message: "+b.ErrorMessage+"     \n";if(c=="ParserError"){a+="XamlFile: "+b.xamlFile+"     \n";a+="Line: "+b.lineNumber+"     \n";a+="Position: "+b.charPosition+"     \n"}else if(c=="RuntimeError"){if(b.lineNumber!=0){a+="Line: "+b.lineNumber+"     \n";a+="Position: "+b.charPosition+"     \n"}a+="MethodName: "+b.methodName+"     \n"}alert(a)};Silverlight.createObjectEx=function(b){var a=b,c=Silverlight.createObject(a.source,a.parentElement,a.id,a.properties,a.events,a.initParams,a.context);if(a.parentElement==null)return c};Silverlight.buildPromptHTML=function(f){var a=null,g=Silverlight.fwlinkRoot,d=Silverlight.ua.OS,b=f.onGetSilverlightClick,c="108739",h="108731",e="Get Microsoft Silverlight",i="0x409";if(!b)b="";else b+="();";if(d=="Windows")c="108732";else if(d=="MacIntel")c="108737";else if(d=="MacPPC")c="108736";a='<div style="display:block; width: 205px; height: 67px;"><img onclick="javascript:Silverlight.followFWLink({0});'+b+'" style="border:0; cursor:pointer" src="{1}" title="'+e+'" alt="'+e+'"/></div>';a=a.replace("{0}",c);a=a.replace("{1}",g+h);return a};Silverlight.__cleanup=function(){for(var a=Silverlight._silverlightCount-1;a>=0;a--){window["__slLoad"+a]=null;window["__slError"+a]=null}if(window.removeEventListener)window.removeEventListener("unload",Silverlight.__cleanup,false);else window.detachEvent("onunload",Silverlight.__cleanup)};Silverlight.followFWLink=function(a){top.location=Silverlight.fwlinkRoot+String(a)};Silverlight.HtmlAttributeEncode=function(c){var a,b="";if(c==null)return null;for(var d=0;d<c.length;d++){a=c.charCodeAt(d);if(a>96&&a<123||a>64&&a<91||a>43&&a<58&&a!=47||a==95)b=b+String.fromCharCode(a);else b=b+"&#"+a+";"}return b}// JScript File
function WatchA(id, custm, objID, objType)
{
    var div = document.getElementById(id);
    if( div == null )
    {
        debugger;
        alert('no reference WatchA');
        return;
    }
    if(custm=="00000000-0000-0000-0000-000000000000")
    {
        alert('添加收藏请先登录');
        return;
     }
    var flat = div.getAttribute("flat");        
    var nflat;
    if( flat == "0" )
        nflat = "1"
    else 
        nflat = "0"
    div.setAttribute("flat",nflat)
    div.children[0].src = '../PublicImg/TDesign/loading.gif';    
    div.children[0].width='18'
    div.children[0].height='18';
    div.children[0].alt='Loading...';
    WSUptWatch.UpdateA(id,flat,custm,objID,objType,OnCompleteWatch);         
}

function WatchB(id, custm, objID, objType)
{    
    var div = document.getElementById(id);
    if( div == null )
    {
        debugger;
        alert('no reference WatchB');
        return;
    }
    if(custm=="00000000-0000-0000-0000-000000000000")
    {
        alert('添加收藏请先登录');
        return;
     }
    var flat = div.getAttribute("flat");        
    var nflat;
    if( flat == "0" )
        nflat = "1"
    else 
        nflat = "0"
    div.setAttribute("flat",nflat)
        
    div.children[0].src = '../PublicImg/TDesign/loading.gif';    
    div.children[0].width='18'
    div.children[0].height='18';
    div.children[1].innerText = 'Please wait';
    div.children[1].runtimeStyle.color = '#808080';
        
    WSUptWatch.UpdateB(id,flat,custm,objID,objType, OnCompleteWatch);    
}

function WatchC(id, custm, style,color, objType)
{    
    var div = document.getElementById(id);
    if( div == null )
    {
        debugger;
        alert('no reference WatchC');
        return;
    }
    if(custm=="00000000-0000-0000-0000-000000000000")
    {
        alert('请先登录');
        return;
     }
    var flat = div.getAttribute("flat");        
    var nflat;
    if( flat == "0" )
        nflat = "1"
    else 
        nflat = "0"
    div.setAttribute("flat",nflat)
        
    div.children[0].src = '../PublicImg/TDesign/loading.gif';    
    div.children[0].width='18'
    div.children[0].height='18';
    div.children[1].innerText = 'Please wait';
    div.children[1].runtimeStyle.color = '#808080';
        
    WSUptWatch.UpdateC(id,flat,custm,style, color,objType, OnCompleteWatch);
}

function WatchD(id, custm, style, color, objType) {
    var div = document.getElementById(id);
    if (div == null) {
        debugger;
        alert('no reference WatchD');
        return;
    }
    if (custm == "00000000-0000-0000-0000-000000000000") {
        alert('请先登录');
        return;
    }
    var flat = div.getAttribute("flat");
    var nflat;
    if (flat == "0")
        nflat = "1"
    else
        nflat = "0"
    div.setAttribute("flat", nflat);
    WSUptWatch.UpdateD(id, flat, custm, style, color, objType, OnCompleteWatch);
}

function OnCompleteWatch(result)
{   
    var id, html;    
    var split = result.indexOf('@');
    id = result.substring(0,split);
    html = result.substring(split+1,result.length);
    var div = document.getElementById(id);
    if( div == null )
    {
        debugger;
        alert('no reference OnComplete');
        return;
    }
    div.innerHTML = html;        
}


if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


function AddToShoppingBag(html, qty, amt, type, freeShipping)
{    
    var isalert = true;
    if (typeof(ShowShoppingBag) != "function")    
    {        
        if (typeof(parent.ShowShoppingBag) == "function")
        {
            isalert = false;
            parent.ShowShoppingBag(html, qty, amt, type, null, freeShipping);        
        }
        if (typeof(parent.HideParentLoadingDiv) == "function")
            parent.HideParentLoadingDiv();
        else
        {
            try
            {
                HideParentLoadingDiv();    
            }
            catch(e) 
            {
                ;
            }            
        }  
        if (typeof(parent.closediv) == "function")
            parent.closediv();
        else
        {
            try
            {
                closediv();    
            }
            catch(e) 
            {
                ;
            }            
        }                        
    }
    else
    {       
        isalert = false; 
        ShowShoppingBag(html, qty, amt, type, null, freeShipping);        
        try
        {
            HideParentLoadingDiv();    
        }
        catch(e) 
        {
            ;
        }            
        try
        {
            closediv();    
        }
        catch(e) 
        {
            ;
        }            
    }    
    if (isalert)
    {
        alert("已经成功加入购物篮");
        window.close();
    }
}

function UpdateEdition(result, hidid, btnid)
{
    if (typeof(UpdateStyleColor) != "function")
    {
        parent.UpdateStyleColor(result, hidid, btnid);        
        if (typeof(parent.HideParentLoadingDiv) == "function")
            parent.HideParentLoadingDiv();
        else
        {
            try
            {
                HideParentLoadingDiv();    
            }
            catch(e) 
            {
                ;
            }            
        }  
        if (typeof(parent.closediv) == "function")
            parent.closediv();
        else
        {
            try
            {
                closediv();    
            }
            catch(e) 
            {
                ;
            }            
        }
    }
    else
    {
        UpdateStyleColor(result, hidid, btnid);        
        HideParentLoadingDiv();
        closediv();
    }    
}

function LoadComment(divcomid, styleid)
{
    var ctl = document.getElementById(divcomid);    
    ctl.innerHTML = '<img src="PublicImg/TDesign/loading.gif" style="margin-left:5px;margin-right:3px;align="/absmiddle"/" width=18 height=18><span>Loading...</span>';       
    WSStyleTopic.GetStyleTopicList1(divcomid, styleid, '', BindResult);    
}

function LoadLifePic(divpic, styleid, labcolor)
{
    var pic = document.getElementById(divpic);
    var lab = document.getElementById(labcolor);        
    var colorid = lab.innerHTML;        
    pic.innerHTML = '<img src="PublicImg/TDesign/loading.gif" style="margin-left:5px;margin-right:3px;align="/absmiddle"/" width=18 height=18><span>Loading...</span>';       
    WSStyleTopic.GetStyleLifePhoto(styleid, colorid, divpic, BindResult);
}

function BindResult(result)
{    
    var id, html;    
    var split = result.indexOf('@');
    id = result.substring(0,split);
    html = result.substring(split+1,result.length);
    
    var ctl = document.getElementById(id);
    if(ctl==null){alert('no reference');return;}    
    ctl.innerHTML = html
    
    if (id == "divlifepic")
    {
        initLightbox();
    }
}

var imgurl;
var orgalt;
var color;
var divvisible;
function PreviewImg(url, id, lnkid, divid, obj)
{    
    var img = document.getElementById(id);     
    var lnk = document.getElementById(lnkid);
    var div = document.getElementById(divid);    
    imgurl = img.src;
    img.src = url;    
    var alt = obj.getAttribute("alt");                    
    if (div != null)
    {
        if (alt != null && alt.length > 0)
        {
            if (div.style.display == 'none')
            {
                divvisible = false;
                div.style.display = 'block';
                lnk.innerHTML = alt;
            }
            else
            {
                divvisible = true;
                orgalt = lnk.innerHTML;
                lnk.innerHTML = alt;
            }
        }
        else
        {
            if (div.style.display == 'block')
            {
                divvisible = true;
                div.style.display = 'none';
            }
        }
    }
}
function RecoverImg(id, lnkid, divid)
{
    var img = document.getElementById(id);
    var lnk = document.getElementById(lnkid);
    var div = document.getElementById(divid);
    if (imgurl != null)    
        img.src = imgurl;        
    if (div != null)    
    {
        if (divvisible)
        {
            div.style.display = 'block';
            if (orgalt != null)
                lnk.innerHTML = orgalt;
        }
        else
        {
            div.style.display = 'none';
            if (orgalt != null)
                lnk.innerHTML = orgalt;
        }
    }
}

function ShowProperty(htmlkey) {
    if (WSLog != null) {        
        WSLog.GetHtmlstring(htmlkey, AJAXResult);
    }
}

function AJAXResult(result) {
    if (result.toString().length <= 0)
        return;
    var Divprop = document.getElementById("Divprop");
    var update = false;
    
    if (Divprop == null) {
        Divprop = document.createElement('div');
        Divprop.style.position = "fixed";
        Divprop.style.borderStyle = "solid";
        Divprop.style.borderWidth = "3px";
        Divprop.style.borderColor = "Gray";
        Divprop.style.zIndex = 10001;
        Divprop.id = "Divprop";
        update = true;
    }
    var content = "<div style=\"position: absolute; top: 0px; right:0px; z-index:2\">";
    content += "<img src=\"../PublicImg/quickLook_close.GIF\" onclick=\"closedivprop();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
    content += "</div><div style='width:600px; height:400px;overflow-y: auto; overflow-x: hidden; background-color:#ffffff'>";
    content += "<div style=\"margin: 5px 5px 5px 5px; width: 566px; height:380px;\">";
    content += result + "</div></div>";
    Divprop.innerHTML = content;
    if (update) {
        document.body.insertBefore(Divprop, null);

        var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

        var clientWidth;
        var clientHeight;
        switch (Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }

        var xCoord = 0;
        var yCoord = 0;

        var foregroundelementwidth = Divprop.offsetWidth ? Divprop.offsetWidth : Divprop.scrollWidth;
        xCoord = ((clientWidth - foregroundelementwidth) / 2);
        Divprop.style.left = xCoord + 'px';
        var foregroundelementheight = Divprop.offsetHeight ? Divprop.offsetHeight : Divprop.scrollHeight;
        yCoord = ((clientHeight - foregroundelementheight) / 2);
        Divprop.style.top = yCoord + 'px';
    }
}

function closedivprop() {
    var div = document.getElementById("Divprop");
    if (div)
        document.body.removeChild(div);
}

function closedivsize() {
    var div = document.getElementById("DivSize");
    if (div)
        document.body.removeChild(div);
}

function ShowSizeSelWiz(styleid, place, gender) {
    var curl = document.URL;
    var hn = document.location.host;

    curl = curl.replace("http://" + hn + "/", "");
    var a = curl.split('/');
    var app = "";
    if (a.length > 2) {
        app = a[0] + "/";
    }
    var simpleurl = "http://" + hn + "/" + app + "SizeSelWiz.aspx?styleID={0}&place={1}&gender={2}";

    var url = simpleurl.replace("{0}", styleid);
    url = url.replace("{1}", place);
    url = url.replace("{2}", gender);

    var Divsize = document.getElementById("DivSize");
    var update = false;

    if (Divsize == null) {
        Divsize = document.createElement('div');
        Divsize.style.position = "fixed";
        Divsize.style.borderStyle = "solid";
        Divsize.style.borderWidth = "3px";
        Divsize.style.borderColor = "Gray";
        Divsize.style.zIndex = 10001;
        Divsize.id = "DivSize";
        update = true;
    }
    var content = "<div style=\"position: absolute; top: 0px; right:0px; z-index:2\">";
    content += "<img src=\"../PublicImg/quickLook_close.GIF\" onclick=\"closedivsize();\" style=\"cursor: hand; width: 15px; height: 15px;\" />";
    content += "</div><div style=\"width:600px; height:400px;\" id=\"divframe\"><iframe style='width:100%; height:100%;overflow-y: auto; overflow-x: hidden; background-color:#ffffff' frameborder=\"0\" scrolling=\"no\" src=\"" + url + "\"/>";
    content += "</div></div>";
    Divsize.innerHTML = content;
    if (update) {
        document.body.insertBefore(Divsize, null);

        var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
        var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

        var clientWidth;
        var clientHeight;
        switch (Sys.Browser.agent) {
            case Sys.Browser.InternetExplorer:
                clientWidth = document.documentElement.clientWidth;
                clientHeight = document.documentElement.clientHeight;
                break;
            case Sys.Browser.Safari:
                clientWidth = window.innerWidth;
                clientHeight = window.innerHeight;
                break;
            case Sys.Browser.Opera:
                clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
                break;
            default:  // Sys.Browser.Firefox, etc.
                clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
                clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
                break;
        }

        var xCoord = 0;
        var yCoord = 0;

        var foregroundelementwidth = Divsize.offsetWidth ? Divsize.offsetWidth : Divsize.scrollWidth;
        xCoord = ((clientWidth - foregroundelementwidth) / 2);
        Divsize.style.left = xCoord + 'px';
        var foregroundelementheight = Divsize.offsetHeight ? Divsize.offsetHeight : Divsize.scrollHeight;
        yCoord = ((clientHeight - foregroundelementheight) / 2);
        Divsize.style.top = yCoord + 'px';
    }
}// JScript File
function LoadTopic(id,styleid,rtnurl)
{
    WSStyleTopic.GetStyleTopicList(id,styleid,rtnurl,BindTopicList);
}

function BindTopicList(result)
{
    var id, html;    
    var split = result.indexOf('@');
    id = result.substring(0,split);
    html = result.substring(split+1,result.length);
    
    var ctl = document.getElementById(id);
    if(ctl==null){alert('no reference');return;}    
    ctl.innerHTML = html
}

function loaddetail(key, topicid, style)
{
    var img = document.getElementById(key+'img');
    var detail = document.getElementById(key+'detail');        
    
    var expand = img.getAttribute('expand');
    if( expand == '0' )
    {        
        detail.innerHTML = '<img src="/PublicImg/TDesign/loading.gif" style="margin-left:5px;margin-right:3px;align="/absmiddle"/" width=18 height=18><span>Loading...</span>';   
        WSStyleTopic.GetStyleTopicByID(key,topicid, style, binddetail);                
    }
    
    if( detail.style.display=='none' )
    {        
        detail.style.display='';        
        img.src='/PublicImg/treeCollaps.gif';
    }
    else
    {
        detail.style.display='none';
        img.src='/PublicImg/treeExpand.gif';
    }
    
}

function binddetail(result)
{
    var key, html;    
    var split = result.indexOf('@');
    key = result.substring(0,split);
    html = result.substring(split+1,result.length);
    
    var img = document.getElementById(key+'img');
    var detail = document.getElementById(key+'detail');  
    
    img.setAttribute('expand','1');
    detail.innerHTML = html;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();function CycleAD(container,width,height,indexarr,contentarr,selectedIndex, autoplay,headercss,selectheadercss )
{
    this._container = $get(container);
    this._indexArray = indexarr;
    this._contentArray = contentarr;
    this._selectedIndex = selectedIndex;
    this._preselectIndex = selectedIndex;
    this._autoPlay = autoplay;
    this._headerCss = headercss;    
    this._selectHeaderCss = selectheadercss;    
    this._width = width;
    this._height = height;
    
    this._panes = [];
    
    this._containerMouseOverHander = null;
    this._containerMouseOutHander = null;
    
    this._duration = 0.35;    
    this._framesPerSecond = 30;
    
    this._indexClickHandler = null;
    this._times=6; 
    this._index = 0;
    
    this.AutoPlay = function()
    {           
        if( !this._autoPlay )
            return;
            
        if( this._times == 1 )
        {
            if( this._index >= this._panes.length )
            {
                this._index = 0;
            }
           this._changeSelectedIndex(this._index, true);
           
           this._index++;
           
           this._times = 6;
        }
        this._times=this._times-1;         
    }
    
    this.initialize = function()
    {
        var constyle = this._container.style;
        constyle.overflow = 'hidden';
        constyle.position='relative';
        if( this._width != undefined && this._width != null )
            constyle.width = this._width +'px';
        if( this._height != undefined && this._height != null )
            constyle.height = this._height + 'px';
            
        this._containerMouseOverHander = Function.createDelegate(this, this._onConMouseOver);
        this._containerMouseOutHander = Function.createDelegate(this, this._onConMouseOut);
        $addHandler(this._container,"mouseover",this._containerMouseOverHander);
        $addHandler(this._container,"mouseout",this._containerMouseOutHander);
        
        this._indexClickHandler = Function.createDelegate(this, this._onIndexClick);
        var index;
        for(index = 0; index < this._indexArray.length; index++){
            var header = $get(this._indexArray[index]);
            var content = $get(this._contentArray[index]);
            if( header == undefined || header == null || content == undefined || content == null )
            {continue;}
            this.addPane(header,content);                                       
        }        
        
        if (this.get_Pane() && this._panes.length > 0) {
            this._changeSelectedIndex(this._selectedIndex, false, true);  
        }              
    }
    
    this.get_Pane = function(index)
    {
        if (index == undefined || index == null) 
        {
            index = this._selectedIndex;
        }
        return (this._panes && index >= 0 && index < this._panes.length) ? this._panes[index] : null;
    }
    
    this.addPane =  function(header, content)
    {
        var pane = { };
        pane.animation = null;        
                
        pane.header = header;
        header._index = this._panes.length;
        $addHandler(header, "click", this._indexClickHandler);                
        pane.content = content;    
        
        Array.add(this._panes, pane);
        
        this._initializePane(header._index);                          
        return pane;       
    }
    
    this._initializePane = function(index)
    {
        var pane = this.get_Pane(index);
        if (!pane) {
            return;
        }
        var header = pane.header;
        var content = pane.content;        
        
        var opened = (index == this._selectedIndex) ? true : false ;        
        content.style.display = opened ? 'block' : 'none';  
        content.style.position='absolute';
                                      
        var opacity = (opened) ? 1 : 0;        
        if ($common.getElementOpacity(content) != opacity) 
        {
            $common.setElementOpacity(content, opacity);
        }        
    }            
    
    this._onIndexClick = function(evt)
    {                                
        var header = evt.target;
        //var accordion = this._container;
        //while (header && (header.parentNode != accordion)) 
        //{
        //    header = header.parentNode;
        //}        
        //evt.stopPropagation();                
        var index = header._index;        
        this._changeSelectedIndex(index, true);
    }
    
    
    this._changeSelectedIndex = function(index, animate, force) 
    {                        
        var lastIndex = this._selectedIndex;
        var currentPane=this.get_Pane(index);
        var lastPane=this.get_Pane(lastIndex);
        if (!force && (currentPane == lastPane)) 
        {
            return;
        }                        
               
        if(lastPane && this._headerCss != '')
        {
            lastPane.header.className = this._headerCss;
        }
                
        if(currentPane)
        {
            currentPane.header.className = (this._selectHeaderCss == '') ? 
                this._headerCss : this._selectHeaderCss;
        }
       
        this._selectedIndex = index;   
        this._index = index;
        this._preselectIndex =  lastIndex;            
                
        if (animate) 
        {
            this._changePanes(lastIndex);
        }                
    }
    
    this._changePanes = function(lastIndex) 
    {                    
        var open = null;
        var close = null;
        var fadein = null;
        
        for (var i = 0; i < this._panes.length; i++)
        {            
            var pane = this._panes[i];
            var animation = this._getAnimation(pane);                                    
            
            if (animation.get_isPlaying()) 
            {                
                animation.stop();                
                $common.setElementOpacity(pane.content,0);                
                pane.content.style.display = 'none';
            }            
            
            if (i == this._selectedIndex) 
            {
                animation._opening = true;
                open = animation;                                
            } 
            else if (i == lastIndex) 
            {
                animation._opening = false;
                close = animation;                                                
            } 
            else 
            {
                continue;
            }
            
            this._startPaneChange(pane, animation._opening);

            animation._fade.set_effect(animation._opening ? Sys.Extended.UI.Animation.FadeEffect.FadeIn : Sys.Extended.UI.Animation.FadeEffect.FadeOut);                        
            animation.set_target(pane.content);                         
        }                              
        
        if (close) 
        {            
            close.play();
        }
        if (open) 
        {            
           open.play();
        }                
    }  
    
    this._startPaneChange = function(pane, opening) 
    {            
        var wrapper = pane.content;        
        
        if (opening) {            
            wrapper.style.display = 'block';
        } else {            
            //wrapper.style.overflow = 'hidden';                                                
        }
    }       
    
    this._getAnimation = function(pane) 
    {               
        var animation = pane.animation;
        if (!animation) {                        
            var fade = null;
            fade = new Sys.Extended.UI.Animation.FadeAnimation(null, null, null, Sys.Extended.UI.Animation.FadeEffect.FadeOut, 0, 1, false);
            animation = new Sys.Extended.UI.Animation.ParallelAnimation(pane.content, this._duration, this._framesPerSecond, [fade]);
            
            pane.animation = animation;            
            animation._fade = fade;
            animation._pane = pane;
            animation._opening = true;
            animation._behavior = this;
            animation._ended = Function.createDelegate(pane.animation, this._onAnimationFinished);
            animation.add_ended(pane.animation._ended);            
            animation.initialize();
        }
        return animation;
    }
    
    this._onAnimationFinished = function() 
    {    
        this._behavior._endPaneChange(this._pane, this._opening);
    }
    
    this._endPaneChange = function(pane, opening) 
    {      
        var wrapper = pane.content;        
        var header = pane.header;
        if (opening) 
        {                                                          
//            wrapper.style.width = (this._contentSize) + 'px'; //'auto';
//            wrapper.style.overflow = 'hidden';//'auto';            
        } else {            
            wrapper.style.display = 'none';                        
        }        
    }  
    
    this._onConMouseOver = function(evt)
    {
       this._autoPlay = false;
    }
    
    this._onConMouseOut = function(evt)
    {
       this._autoPlay = true;
    }               
    
    this.initialize();
}var btnfitid;
var hidden;
var divpanel;
var isFF;
var iTimer1;
var iTimer2;
var pos = 0;
var openfittingroom = false;
function InitFittingRoom(btn, hid)
{
    btnfitid = btn;
    hidden = document.getElementById(hid);    
}

function PreviewFitting(style, color)
{     
    hidden.value = style + '-' + color;          
    var ctl = document.getElementById(btnfitid);    
    ctl.click();    
    if (!openfittingroom)
    {
        ShowFittingRoom();
        openfittingroom = true;
    }
}

function continuescrollup(id)
{
    divpanel = document.getElementById(id);    
    clearTimeout(iTimer2);    
    pos = divpanel.scrollTop;
    pos=pos-10;        
    if (pos < 0)
    {
        clearTimeout(iTimer1);
        pos = 0;
    }
    else
    {
        divpanel.scrollTop = pos;
        iTimer1 = setTimeout("continuescrollup('" + id + "')", 100);
    }    
}
function continuescrolldown(id)
{
    divpanel = document.getElementById(id)    
    clearTimeout(iTimer1);    
    pos = divpanel.scrollTop;
    pos=pos+10;        
    if (pos > divpanel.scrollHeight - divpanel.clientHeight)
    {
        clearTimeout(iTimer2);
        pos = divpanel.clientHeight;
    }
    else
    {
        divpanel.scrollTop = pos;
        iTimer2 = setTimeout("continuescrolldown('" + id + "')", 100);
    }    
}
function stopscroll()
{         
    clearTimeout(iTimer2);
    clearTimeout(iTimer1);   
}

function ShowFittingRoom()
{
    var img = $get("imgfitting");
    if (!img)
        return;    
        
    var hideimg = "hidefittingroomcss";//http://www.e-giordano.com/PublicImg/FittingRoom/hidefitting.gif";
    var showimg = "showfittingroomcss";//http://www.e-giordano.com/PublicImg/FittingRoom/showfitting.gif";
    var curimg = img.className.toString();//img.src.toString().toLowerCase();
    var avce = $find("popupSimplyFittingRoom");
    var obj = avce.get_element();
    var tdpanel1 = $get("tdpanel1");
    var tdpanel2 = $get("tdpanel2");    
    if (curimg.indexOf(hideimg.toLowerCase(), 0) == -1)
    {   
        var sAgent = navigator.userAgent.toLowerCase();
        isFF = (sAgent.indexOf("ie") == -1);
        img.className = hideimg;                                             
        tdpanel2.style.visibility = "visible";
        if (isFF)
            tdpanel1.style.display = "table-cell";
        else
            tdpanel1.style.display = "block";
        if (tdpanel2.style.display == "none")        
            obj.style.width = img.clientWidth + tdpanel1.clientWidth + "px";
        else
        {            
            obj.style.width = img.clientWidth + tdpanel1.clientWidth + tdpanel2.clientWidth + "px";
        }
    }        
    else
    {
        img.className = showimg;                
        tdpanel1.style.display = "none";   
        tdpanel2.style.visibility = "hidden";             
        obj.style.width = img.clientWidth + "px"; 
        obj.style.overflow = "hidden";           
        openfittingroom = false;
    }
    avce._reposition();    
}

function ShowTDPanel2()
{
    var img = $get("imgexpend");
    var img2 = $get("imgfitting");
    if (!img || !img2)
        return;
    var openimg = "openrightcss";//"http://www.e-giordano.com/PublicImg/FittingRoom/open.gif";
    var closeimg = "closerightcss";//"http://www.e-giordano.com/PublicImg/FittingRoom/close.gif";
    var curimg = img.className.toString();
    
    var avce = $find("popupSimplyFittingRoom");
    var obj = avce.get_element();    
    var tdpanel2 = $get("tdpanel2");
    var tdpanel1 = $get("tdpanel1");        
    var sAgent = navigator.userAgent.toLowerCase();
    isFF = (sAgent.indexOf("ie") == -1);                
    if (curimg.indexOf(openimg.toLowerCase(), 0) == -1)    
    {
        //alert(img2.clientWidth + tdpanel1.clientWidth + "px");
        img.className = openimg;
        tdpanel2.style.display = "none";
        obj.style.width = img2.clientWidth + tdpanel1.clientWidth + "px";
    }
    else
    {             
        img.className = closeimg;       
        if (isFF)
            tdpanel2.style.display = "table-cell";        
        else
            tdpanel2.style.display = "block";
        obj.style.width = img2.clientWidth + tdpanel1.clientWidth + tdpanel2.clientWidth + "px";
    }
    avce._reposition();
}if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();
