YAHOO.namespace("sde.sdehelp");

function mailTo(template, email, name, ref) {
    var url = "/do/MailFormNew/?";
    url = url + "TMPL=" + encodeURI(template);
    url = url + "&EMAIL=" + encodeURI(email);
    if (name) {
        url = url + "&TO=" + encodeURI(name);
    }
    if (ref) {
        url = url + "&REF=" + encodeURI(ref);
    }

    thewindow=window.open(url,'mnew','height=640,width=740,toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,directories=no,status=yes');
}

function getHelp(pageName, param1, param2) {
    var url  = "/av/index.cgi?";
    var params = "action=cmsLitePage&page=" + escape(pageName);
    var title = "Help";
    if (param2) {
        title = param2;
    }
    var width = "350px";
    if (param1) {
        width = param1;
    }
    var ctx = null;
    getYUIPanel(url, params, title, width, ctx);
}

function getYUIPanel(url, params, title, width, ctx) {
    var sUrl = url + params;
    
    var handleSuccess = function(o) {
        var response = o.responseText;
        yuiHelpWindow(response, title, width, ctx);
    };

    var handleFailure = function(o) {
        var errMessage = "Error: " + o.status;
        yuiHelpWindow(errMessage);
    };
    var callback = { success: handleSuccess, failure: handleFailure };
    var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
}

function getCountryChangeWindow(ctx, opts) {
    var sUrl = '/av/index.cgi?op=chcountryform';
    if (opts) {
        sUrl = sUrl + "&" + opts;
    }

    var handleSuccess = function(o) {
        var response = o.responseText;
	    YAHOO.sde.sdehelp.helpPanel = new YAHOO.widget.Panel("helpPanel", { 
            context: [ctx, "tr", "br" ], 
            width: "280px", 
            visible:false, 
            constraintoviewport:true, 
            iframe:true 
        } ); 
        YAHOO.sde.sdehelp.helpPanel.setHeader("Change country"); 
        YAHOO.sde.sdehelp.helpPanel.setBody(response); 
        YAHOO.sde.sdehelp.helpPanel.render("helpContainer");
        YAHOO.sde.sdehelp.helpPanel.show();
    };

    var handleFailure = function(o) {
        var errMessage = "Error: " + o.status;
        yuiHelpWindow(errMessage);
    };
    var callback = { success: handleSuccess, failure: handleFailure };
    var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
}

function getCcyChangeWindow(ctx, opts) {
    var sUrl = '/av/index.cgi?op=chccyform';
    if (opts) {
        sUrl = sUrl + "&" + opts;
    }

    var handleSuccess = function(o) {
        var response = o.responseText;
	    YAHOO.sde.sdehelp.helpPanel = new YAHOO.widget.Panel("helpPanel", { 
            context: [ctx, "tr", "br" ], 
            width: "250px", 
            visible:false, 
            constraintoviewport:true, 
            iframe:true 
        } ); 
        YAHOO.sde.sdehelp.helpPanel.setHeader("Change currency"); 
        YAHOO.sde.sdehelp.helpPanel.setBody(response); 
        YAHOO.sde.sdehelp.helpPanel.render("helpContainer");
        YAHOO.sde.sdehelp.helpPanel.show();
    };

    var handleFailure = function(o) {
        var errMessage = "Error: " + o.status;
        yuiHelpWindow(errMessage);
    };
    var callback = { success: handleSuccess, failure: handleFailure };
    var transaction = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback, null);
}

function yuiHelpWindow(content, title, width, ctx) {
	// Instantiate a Panel from script
    YAHOO.log("Instantiate a Panel from script");
    if (ctx) {
	    YAHOO.sde.sdehelp.helpPanel = new YAHOO.widget.Panel("helpPanel", { context: [ctx, "tl", "bl" ], width:width, visible:false, constraintoviewport:true, iframe:true } ); 
    }
    else {
	    YAHOO.sde.sdehelp.helpPanel = new YAHOO.widget.Panel("helpPanel", { width:width, visible:false, constraintoviewport:true, iframe:true } ); 
    }
	YAHOO.sde.sdehelp.helpPanel.setHeader(title); 
	YAHOO.sde.sdehelp.helpPanel.setBody(content); 
	YAHOO.sde.sdehelp.helpPanel.render("helpContainer");
    YAHOO.sde.sdehelp.helpPanel.show();
}

function openPanel (url, winWidth, winHeight) {
    if (winHeight == null) {
        winHeight = parseFloat(winWidth)/1.618;
    }
    var winParams = "width=" + parseInt(winWidth) + ",height=" + parseInt(winHeight) + ",resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,menubar=no,copyhistory=no,status=no";

    window.open(url,'panelWindow',winParams);
}

function hideDiv(divName) {
    var tempDiv=YAHOO.util.Dom.get(divName);
    
    if(!tempDiv){
        return;
    }

    if(tempDiv.style.display=="inline") {
        YAHOO.util.Dom.addClass(tempDiv,"wasInline");
    }
    else if (tempDiv.style.display=="block") {
        YAHOO.util.Dom.addClass(tempDiv,"wasBlock");
    }
    
    tempDiv.style.display="none";
}

function showDiv(divName) {
    var tempDiv=YAHOO.util.Dom.get(divName);
    
    if (!tempDiv) {
        return;
    }
    
    if (YAHOO.util.Dom.hasClass(tempDiv,"wasInline")) {
        tempDiv.style.display="inline";
        YAHOO.util.Dom.removeClass(tempDiv,"wasinline");
    }
    else if (YAHOO.util.Dom.hasClass(tempDiv,"wasBlock")) {
        tempDiv.style.display="block";
        YAHOO.util.Dom.removeClass(tempDiv,"block");
    } else {
        tempDiv.style.display=getDisplayStyleByTagName(tempDiv);
    }
}

function getDisplayStyleByTagName(o){
    var n=o.nodeName.toLowerCase();
    return( n=="span" || n=="img" || n=="a" ) ? "inline" : ( n=='tr' || n== 'td' ? "" : "block" );
}

var UT_RATING_IMG='star_full_19x20';
var UT_RATING_IMG_HALF='star_half_19x20';
var UT_RATING_IMG_BG='star_empty_19x20';

function StarRating(ratingElementId, maxStars, objectName, formName, ratingMessageId, size, messages, starCount, callback) {
    this.ratingElementId=ratingElementId;
    this.maxStars=maxStars;
    this.objectName=objectName;
    this.formName=formName;
    this.ratingMessageId=ratingMessageId;
    this.messages=messages;
    this.callback=callback;
    this.starTimer=null;
    this.starCount=0;
    
    if (starCount) {
        this.starCount=starCount;
        var that=this;
        YAHOO.util.Event.onDOMReady( function() {
            that.drawStars(that.starCount,true);
        });
    }
    
    function showStars(starNum, skipMessageUpdate) {
        this.clearStarTimer();
        this.greyStars();
        this.colorStars(starNum);
        if(!skipMessageUpdate) this.setMessage(starNum);
    }
    
    function setMessage(starNum) {
        if ( starNum > 0 ) {
            if(!this.savedMessage) {
                this.savedMessage=YAHOO.util.Dom.get(this.ratingMessageId).innerHTML;
            }
            YAHOO.util.Dom.get(this.ratingMessageId).innerHTML=this.messages[starNum-1];
        } else if (this.savedMessage) {
            YAHOO.util.Dom.get(this.ratingMessageId).innerHTML=this.savedMessage;
        }
    }
    
    function colorStars(starNum) {
        var fullStars = Math.floor(starNum + 0.25);
        var halfStar=(starNum - fullStars > 0.25);
        for (var i=0; i < fullStars; i++) {
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG_HALF);
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG_BG);
            YAHOO.util.Dom.addClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG);
        }
        
        if (halfStar) {
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG);
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG_BG);
            YAHOO.util.Dom.addClass(YAHOO.util.Dom.get('star_'+ (i+1)), UT_RATING_IMG_HALF);
        }
    }
    
    function greyStars(){
        for(var i=0;i<this.maxStars;i++){
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG);
            YAHOO.util.Dom.removeClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG_HALF);
            YAHOO.util.Dom.addClass(YAHOO.util.Dom.get('star_' + (i+1)), UT_RATING_IMG_BG);
        }
    }

    function setStars(starNum) {
        this.starCount=starNum;
        this.drawStars(starNum);
        var formObject = YAHOO.util.Dom.get(this.formName);
        formObject.rating.value=this.starCount;
        var ratingElementId=this.ratingElementId;
        that=this;
        
        var responseSuccess = function(o) { 
            var txt = o.responseText;
            YAHOO.util.Dom.get(that.ratingElementId).innerHTML=txt;
            if(that.callback){
                that.callback();
            }
        }
        
        var responseFailure = {}; 
        
        var callback = { 
            success: responseSuccess, 
            failure: responseFailure, 
            cache: false
            };
        var submitUrl = formObject.action;
        YAHOO.util.Connect.setForm(formObject);
        YAHOO.util.Connect.asyncRequest('POST', submitUrl, callback);
    }

    function drawStars(starNum, skipMessageUpdate) {
        this.starCount=starNum;
        this.showStars(starNum,skipMessageUpdate);
    }

    function clearStars() {
        this.starTimer=window.setTimeout(this.objectName+".resetStars()",300);
    }

    function resetStars() {
        this.clearStarTimer();
        if(this.starCount)
            this.drawStars(this.starCount);
        else
            this.greyStars();
        this.setMessage(0);
    }

    function clearStarTimer() {
        if(this.starTimer) {
            window.clearTimeout(this.starTimer);
            this.starTimer=null;
        }
    }

    this.clearStars=clearStars;
    this.clearStarTimer=clearStarTimer;
    this.greyStars=greyStars;
    this.colorStars=colorStars;
    this.resetStars=resetStars;
    this.setStars=setStars;
    this.drawStars=drawStars;
    this.showStars=showStars;
    this.setMessage=setMessage;
}
    
function initProductTabs(pid, isCompatiblesTabSelected) {
    YAHOO.log("isCompatiblesTabSelected:"+isCompatiblesTabSelected);

    YAHOO.sde.product.tabView = new YAHOO.widget.TabView('pTabs');
    var tabView = YAHOO.sde.product.tabView;
    tabView.addListener('activeTabChange', chTab);
    var dataSrc = "/do/pcompat/?PID=" + pid;
    var compatTab = new YAHOO.widget.Tab({ 
        label: 'Compatible Products',
        dataSrc: dataSrc,
        dataTimeout: 10000,
        cacheData: true
    });

    if (isCompatiblesTabSelected == 1) {
        compatTab.set('active', true);
    }
    
    tabView.addTab(compatTab);
}

function chTab(e) {
    var tabView = YAHOO.sde.product.tabView;
    var tabIndex = this.getTabIndex(e.newValue);
    var newTab  = tabView.getTab(tabIndex);
    var contentEl = newTab.get('contentEl');
    var newTabID = contentEl.id;
    if (!newTabID) {
        if (newTab.get('label') == 'Compatible Products') {
            newTabID = 'Compatibles';
        }
    }
    var baseAddToCartURL = YAHOO.sde.product.addToCartURL;
    baseAddToCartURL = baseAddToCartURL + "&amp;TAB=" + newTabID;
    if (YAHOO.util.Dom.inDocument('mainAddToCartLink')) { 
        var l = YAHOO.util.Dom.get('mainAddToCartLink');
        YAHOO.util.Dom.setAttribute(l, 'href', baseAddToCartURL);
    }
}

function initProductCarousel(images) {

    YAHOO.sde.product.carousel = new YAHOO.widget.Carousel("imgContainer", {
        numItems: images,
        numVisible: 5,
        revealAmount: 40
    });

    YAHOO.sde.product.carousel.addListener("itemSelected", onProductGalleryIconClick); 

    YAHOO.sde.product.carousel.render(); 
    YAHOO.sde.product.carousel.show();
    YAHOO.log("Carousel initialised");
}

function onProductGalleryIconClick(index) {
    YAHOO.log(index);
    
    var item = YAHOO.sde.product.carousel.getElementForItem(index); 
    YAHOO.log(YAHOO.lang.dump(item));

    if (item) { 
        var attachUUID = item.id;
        YAHOO.log("Attach UUID: " + attachUUID);
        loadProductImage(attachUUID, 'small');
    } 
}

function loadProductImage(attachUUID, size) {
    
    var url     = "/do/PAttachGetScaledImage/?UUID=" + encodeURIComponent(attachUUID) + "&SIZE=" + size;

    YAHOO.log("URL: " + url);
    
    var onSuccess = function(o) {
        var response = o.responseText;
        var respData = {};
        try { 
            respData = YAHOO.lang.JSON.parse(response); 
            YAHOO.log(YAHOO.lang.dump(respData));
        } 
        catch (e) { 
            alert("Error! Invalid product data (failed parsing JSON response)"); 
        }
        
        if (respData.STATUS == '200') {
            var imgUrl = respData.URL;
            YAHOO.log("new url: " + imgUrl);

            var imgX = respData.XSIZE;
            var imgY = respData.YSIZE;
            YAHOO.log("X,Y: " + imgX + "," + imgY);

            var spotlight = YAHOO.util.Dom.get("spotlight");
            var newImageHTML = "<img src=\"" + imgUrl + "\" width=" + imgX + " height=" + imgY + ">";
            YAHOO.log(newImageHTML);
            spotlight.innerHTML = newImageHTML;
        }
        else {
            YAHOO.log("Status: " + respData.STATUS);
        }

    };

    var onFailure = function() {
    };

    var callback = { 
        success: onSuccess, 
        failure: onFailure, 
        cache: false
    };

    YAHOO.util.Connect.asyncRequest('GET', url, callback);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
