/**
*	@name				Wep Pane
*	@version			2.0
*	@author				Nexum Creative
*
*/

//global variables
var wep = {};

wep.blankPageUrl = 'blank.htm'; //set this to the *relative* location of the new "blank.htm" file - *must* be on the same domain as current page


wep.isAccessiblePage = false;
wep.currentButtonId = null;
wep.currentButtonNum = null;
wep.buttonId = null;
wep.version = null;
wep.btnAry = Array();
wep.siteId = null;
wep.catId = '';
wep.subCatId = '';
wep.selectedCatId = null;
wep.sectionId = null;
wep.currentBtn = '';
wep.expandFirstTime = true;
wep.isExpand = false;
wep.numMenuItems = null;
wep.numButtons = null;
wep.selectedItemId = null;
wep.paneData = null;
wep.layout = null;
wep.locale = null;
wep.feedDomainFNP = null;
wep.feedDomainTBN = null;
wep.paneServerUrl = null;
wep.contractFirst = true;


wep.omn = {};
wep.omn.track = false;
wep.omn.country = '';
wep.omn.language = '';
wep.omn.brand = '';
wep.omn.trackingAccount = '';
wep.omn.siteUrl = '';
wep.omn.audience = '';

wep.ubertag = false;

wep.basket = {};
wep.basketFeed = null;


function wde(){};
var jsr = {}; //JSON Script Request


// Dummy Omniture variables - For test purposes only

function s_gi(throwaway){
    this.linkTrackVars = '';
    this.prop1;
    this.prop2;
    this.prop3;
    this.prop4;
    this.prop5;
    this.prop45;
    this.prop46;
    this.eVar45;
    this.prop44;
    this.tl = function (one, two, three){};
    return this;
}
/**/


//dimensions parameters
wep.expandedWidth = 500;
wep.expandedHeight = 480;
wep.expandedWidthMargin = 20;
wep.expandedScrollWith = 17;
wep.expandedHeightMargin = -15;
wep.expandedLeftMargin = -167;
wep.expandedTopMargin = 52;
wep.singleExpandedLeftMargin= 100;  
wep.expanderPageScrollerTopMargin = 30;
wep.expanderPageScrollerBottomMargin = 5;
wep.teaserItemWidth = 232;
wep.teaserItemHeight = 150;
wep.bigIframeWidth = 800;
wep.bigIframeHeight = 500;
wep.smallIframeWidth = 232;
wep.smallIframeHeight = 150;
wep.bigIframeWidthMargin = 18;
wep.loadingIconSize = 36;

//default column count
wep.defaultColumnCount = 4;

//button delay parameters
wep.delayTime  = 250;
wep.btnTimer = null;
wep.btnDelegate = null;
wep.crntBtnNumber = 0;


//performans 
wep.useCacheLazyLoad = true;
wep.useCachedFeed = true;
wep.cachedFeed = new Array();
wep.buttonFeed = null;
wep.lockWebPaneInit = false;

//elements
wep.mask;
wep.popup;
wep.expandedContent;
wep.loading;
wep.exppge;
wep.fader;
wep.currButtonType;
wep.expanderIframe;
wep.bottomborder;
wep.getTeaserType;
wep.getTeaserIframe;
wep.getTeaserBehavior;
wep.buttonContainer;
wep.buttonNum = null;


//flags
wep.expanding = false;
wep.show = false;
wep.gettingData = false;
wep.paneGettingData = false;
wep.IsBigIframeItem = false;
wep.IsSingleListItem = false;

//other
wep.windowedElem = new Array();
wep.tryCount = 0;
wep.numButtons = 0;
wep.mouseIsOver = true;
var iframeLoaded = false;

/**
* Wep pane constructor
* @constructor
*/
wep.constructor = function(){
	// feed variables
	wep.setFeedDomainProtocol();

    wep.buttonServerUrl = wep.feedDomainTBN + '/tbn/' + wep.siteId + '/' + wep.locale.replace('_', '/') + "/";

    if (wep.version != null) {
        wep.buttonServerUrl += wep.version + "/"; 
    }

    // Call the JSON for menu button
    this.getButtonData();
	
    // Intialize web panel layer elements
    this.initialise();

    // Bind to windows resize event
    window.onresize = this.resizeOverlay;
	
    iframeLoaded = false;
};



/**
* Add new data item to cache
* @param {Object} Feed
*/
wep.addDataCache = function(data) {

    if(this.cachedFeed == null) return;

    this.cachedFeed[this.cachedFeed.length] = data;		
	
}

/**
* Lazy data load on windows load event
*/
wep.lazyLoad = function() {

    if(!this.useCacheLazyLoad) return;
		
    this.lockWebPaneInit = true;
    for (var I = 0 ; I < this.buttonFeed.length ; I++) {
			
        var _paneServerUrl = this.feedDomainFNP + '/fnp/' + this.buttonFeed[I].id + '/' + this.locale.replace('_', '/') + '/';
			
        var jsrOb = new jsr.JsonScriptRequest(_paneServerUrl);
        jsrOb.buildScriptTag();
        jsrOb.addScriptTag();			
			
    }
	
}


/**
* Get cached item by button ID
* @param {String} Button ID
* @return Cached feed object
*/
wep.getCachedData = function(buttunId) {
	
    if(this.cachedFeed != null)
    {
        for (var i = 0 ; i < this.cachedFeed.length ; i++) {
            if(this.cachedFeed[i].id != null)
            {
                if(this.cachedFeed[i].id == buttunId) 
                    return this.cachedFeed[i];
            }
        }	
    }
	
    return null;
}


/**
* Is cached item
* @param {String} Button ID
* @return boolean
*/
wep.isCachedItem = function(buttunId) {
	
    if(this.cachedFeed != null)
    {
        for (var i = 0 ; i < this.cachedFeed.length ; i++) {
            if(this.cachedFeed[i].id != null)
            {
                if(this.cachedFeed[i].id == buttunId) 
                    return true;
            }
        }	
    }
	
    return false;
}


/**
* JSON data request object
* This function assign to local variwepable
* @param {String} JSON Service URL
*/
jsr.JsonScriptRequest = function(fullUrl) {
    this.fullUrl = fullUrl; 
    this.head = document.getElementsByTagName("head").item(0);
    this.siteId = '?siteid=' + wep.siteId;
    this.buttonId = '&btnid=' + wep.buttonId;
    this.catId = '&catid=' + wep.catId;
    this.subcatId = '&subid=' + wep.subCatId;
}


/**
* Build script tag by service paramters
*/
jsr.JsonScriptRequest.prototype.buildScriptTag = function () {
    this.scriptObj = document.createElement("script");
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.siteId + this.buttonId + this.catId + this.subcatId);
}

/**
* Remove script tag from page header
*/
jsr.JsonScriptRequest.prototype.removeScriptTag = function () {
    this.head.removeChild(this.scriptObj);  
}


/**
* Clean unused script tag from page header
* @param {String} Script element URL
*/
jsr.JsonScriptRequest.prototype.cleanScriptTag = function (scriptUrl) {
   
    var scriptsTags = document.getElementsByTagName("script");
	
    if(scriptsTags!= null && scriptsTags.length > 0)
    {
        for (var i = 0 ; i < scriptsTags.length ; i++) {
				
            if(scriptsTags[i].src == scriptUrl)
            {
                this.head.removeChild(scriptsTags[i]); 	
            }
        }
    }
}


/**
* Add script tag to page header
*/
jsr.JsonScriptRequest.prototype.addScriptTag = function () {
    this.cleanScriptTag(this.scriptObj.src);
    this.head.appendChild(this.scriptObj);
}


/**
* Parsing feed  domain protocol
*/
wep.setFeedDomainProtocol = function (){
    if(document.location.href.slice(0,6) == 'https:')
    {
        if(this.feedDomainTBN.slice(0,5) == 'http:') this.feedDomainTBN = 'https:' + this.feedDomainTBN.slice(5);
        if(this.feedDomainFNP.slice(0,5) == 'http:') this.feedDomainFNP = 'https:' + this.feedDomainFNP.slice(5);
    }
}

/**
* Load JSON data for menu button with script loader
*/
wep.getButtonJsonData = function(){
    var jsrOb = new jsr.JsonScriptRequest(this.buttonServerUrl);      
    jsrOb.buildScriptTag();  
    jsrOb.addScriptTag();
}


/**
* Asynchronous getting JSON data for menu  button 
*/
wep.getButtonData = function(){
    if(document.body == null) {
        if(this.tryCount<100)setTimeout('this.getButtonData()',100);
        this.tryCount++;
    }
    else this.getButtonJsonData();
}
 
 
/**
* Create menu button and binding menu action
* @param {Object} Feed data (JSON)
*/ 
wep.topbar = function(data){
    if(data!=null){
        var item;
        var labelText;
        var altText;
        var buttonId;
        var buttonType;
        var buttonHTML = '';
        var buttonDiv = document.getElementById('wep_buttons');
        var topBarSpacerUrl = data.feed[0].icon;
        var currentBtnClass;
	
    
        // Setting button feed 
        this.buttonFeed = data.feed[0].entry;
	
        // Setting search box visibility 
        if(data.feed[0].isSearchEnabled == 'True') {
            document.getElementById('wep_searchArea').style.display = 'block';
        }
	
        // Setting button length
        this.numButtons = data.feed[0].entry.length;
        var ii = 0;

        for (var I = 0 ; I < data.feed[0].entry.length ; I++) {
            item = data.feed[0].entry[I];

		
            var contextFlag = false;
            if (item.context == undefined) {
                contextFlag = true;
            } else {
                var inter = wep.intersection(item.context, wep.currentPageContext);
                contextFlag = wep.isArrayNotEmpty(inter) || item.context == '';
            }
            if(contextFlag) {

                // Assigning local variables value
                buttonId = item.id;
                labelText = item.title;
                altText = item.summary;
                buttonType = item.type;
                currentBtnClass = ((this.currentButtonType != null) && (buttonType == this.currentButtonType)) ? "active" : "" 
			
                buttonDiv.className = (this.isAccessiblePage) ? 'accessible' : '';
			
                this.btnAry[ii] = new Array(1);
                this.btnAry[ii][0] = buttonId;
                this.btnAry[ii][1] = buttonType;
	
			
                buttonHTML += '<a href="';
                var accesibleUrl = '';
                if (item.accessible_link != undefined) {
				
                    if(item.accessible_link.href.match('/wep/ViewAccessibleWep.action')){
                    	accesibleUrl = item.accessible_link.href;
    					if (accesibleUrl.indexOf("?") == -1) {
    						accesibleUrl += '?';
    					}
    					if (accesibleUrl.indexOf("=") != -1) {
    						accesibleUrl += '&';
    					}
    					accesibleUrl += "url=" + item.link[0].href + "/html/&type=" + item.type;
    					
                        if(item.accessible_link.href.indexOf("http") == -1 || item.accessible_link.href.indexOf("www") == -1) {
                            accesibleUrl = 'http://' + document.domain + accesibleUrl;
                        }
                        else {
                            accesibleUrl = accesibleUrl;
                        }
                    }else{
                        accesibleUrl = item.accessible_link.href;
                    }
				
                    buttonHTML += accesibleUrl;
                } else {
                    buttonHTML += "javascript:void(0);";
                }
			
                // Create button HTML
                buttonHTML += '"  rel="'+currentBtnClass+'"  class="wep_button '+currentBtnClass+'" id="wep_button' + ii + '" onclick="try{omnitureWEPButtonClick(\''+item.type+'\');wep.openUrl(\''+accesibleUrl+'\',' + null + ')}catch(e){}" onmouseover="try{wep.menudelay(\'' + buttonId + '\',' + ii + ',\'' + buttonType + '\',\'' + this.currentButtonType + '\')}catch(e){};try{wep.hoverButton()}catch(e){}" onmouseout="try{wep.outButton(\'' + ii + '\')}catch(e){}"><span class="btn-left"></span><span>' + labelText + '</span><span class="btn-right"></span></a>';

                ii++
            }
            else {
                this.numButtons--
            }

        }
	
        // Append button HTML
        buttonDiv.innerHTML = buttonHTML;
	
        this.lazyLoad();

    }
}


/**
* Menu delay  function
* @param {Int} Button ID
* @param {Int} Button Number
* @param {String} Button Type
* @param {String} Current Button ID
*/ 
wep.menudelay =function(btnId, btnNum, btnType)
{			
    if (this.mouseIsOver) {
        this.bindOverlayEvents();
    } else {
        this.unBindOverlayEvents();
    }
	
    this.lockWebPaneInit = false;

    // The current  button id is in accessible page
    if(this.isAccessiblePage && (btnType == this.currentButtonType)) 
    {
        this.clearTimer();
        this.btnDelegate = null
				
    } else {
		
        // Layer delegate
        this.btnDelegate = function() {
            wep.showmenu(btnId, btnNum, btnType);
					
            // Accessible page button manipulation
            wep.butttonCollection = document.getElementById("wep_buttons").getElementsByTagName("a");
						
            for(var i=0; i < wep.butttonCollection.length; i++) {
                if(wep.butttonCollection[i].className=="wep_button active") {
                    wep.butttonCollection[i].className = "wep_button";
                }
            }
        }	
			
    }
		
}
	
/**
* Clear menu button delay timer
*/ 	
wep.clearTimer = function(){
    clearTimeout(this.btnTimer)
    this.btnTimer= null;
    this.btnDelegate = null;
}	

/**
* Binding overlay action purpose of web pane close
* @param {Int} Button ID
*/ 
wep.bindOverlayEvents = function(buttonId){
	
    // Onmouseover
    this.fader.onmouseover = function() {	
        wep.selectButton(wep.buttonId);
        wep.currentBtn='';
        wep.closePane();
    }		
		
    // Onclick		
    this.fader.onclick = function() {	
        wep.selectButton(wep.buttonId);
        wep.currentBtn='';
        wep.closePane();
    }	
		
    // Bind button wrapper mauseover events
    this.buttonContainer.onmouseout = this.bindButtonWrapperEvents ;
	
    // Bind content wrapper mauseover events
    this.expandedContent.onmouseout = this.bindContentWrapperEvents ;	
			
}

/**
* Unbinding overlay action purpose of web pane close
* @param {Int} Button ID
*/ 
wep.unBindOverlayEvents = function(buttonId){
	
    // Onmouseover
    this.fader.onmouseover = null;	
		
    // Onclick		
    this.fader.onclick = null;
		
    // Bind button wrapper mauseover events
    this.buttonContainer.onmouseout = this.bindButtonWrapperEvents;
	
    // Bind content wrapper mauseover events
    this.expandedContent.onmouseout = this.bindContentWrapperEvents;	
			
}

/**
* Button wrappers event
* @param {Object} Mause event
*/ 
wep.bindButtonWrapperEvents = function( e )
{
    var relTarg;
    if (!e) var e = window.event;
    if (e.relatedTarget) relTarg = e.relatedTarget;
    else if (e.toElement) relTarg = e.toElement;
      
    if(typeof(relTarg) != 'undefined' )
    {
        if(relTarg.tagName == 'SPAN' || relTarg.tagName == 'A' || relTarg.tagName == 'IFRAME' ) {
        } else {
            if(relTarg.tagName == 'DIV' ) {
                if(relTarg.id == 'wep_buttonArea' || relTarg.id == 'cntHeader' || relTarg.id == 'wepLanguageCommerceContainer' || relTarg.id == 'cntHeaderRow' )
                {
                    setTimeout (
                        function() {
                            wep.selectButton(wep.buttonId);
                            wep.currentBtn='';
                            wep.closePane();	
                        },100);
                }
            }
        }
    }
	  
}

/**
* Content wrappers event
* @param {Object} Mause event
*/ 
wep.bindContentWrapperEvents = function( e )
{
    wep.bindOverlayEvents();
    var relTarg;
    if (!e) var e = window.event;
    if (e.relatedTarget) relTarg = e.relatedTarget;
    else if (e.toElement) relTarg = e.toElement;
      
    if(typeof(relTarg) != 'undefined' )
    {
        if(relTarg.tagName == 'DIV' && relTarg.id == 'cntHeader' ) {
            setTimeout (
                function() {
                    wep.selectButton(wep.buttonId);
                    wep.currentBtn='';
                    wep.closePane();	
                },100);
				
        }
			
			
    }
	  
}

/**
* Menu button hover action (onmouseover event)
*/ 
wep.hoverButton = function(){

    // Create new timer instiance
    this.btnTimer = setTimeout(
        function() {
            if(wep.btnDelegate != null && typeof(wep.btnDelegate)== 'function') {
                wep.btnDelegate()
            }
        },this.delayTime);
	
    wep.isMenuHover = true;
}

/**
* Menu button hover action (onmouseout event)
* @param {Int} Current Button ID
*/ 
wep.outButton = function(buttonId){

    // Apply link style
    var button = document.getElementById('wep_button' + buttonId);
	
    if(button.rel != 'undefined' && button.rel == 'active')  return;
	
    if(!wep.hasClass(button, 'wep_buttonSelected')){
        button.className = 'wep_button';
    }
	
    // Clear menu delay 
    this.clearTimer();
	
    // Clear menu delay  delegate	
    this.btnDelegate = null;
    wep.isMenuHover = false;
	
}

/**
* Determine whether any of the matched elements are assigned the given class.
* @param {Object} Dom Element
* @param {String} Class Name
*/ 
wep.hasClass = function (object, className){
    if(object){
        if(object.getAttribute('class')==className || object.getAttribute('className')==className)
            return true;
    }
    return false;
}   


/**
* Show wep pane layer
*/ 
wep.showPane = function() {
    if(wep.isIE6()) {
        this.mask.style.visibility = 'visible';
    }
    this.expandedContent.style.visibility = 'visible';
    this.expandedContent.style.display = 'block';
}

/**
* Close wep pane layer
*/ 
wep.closePane = function() {
    if(wep.isIE6()) {
        this.mask.style.visibility = 'hidden';
    }
    this.expandedContent.style.visibility = 'hidden';	
    this.clearExpanderPage();
    this.gettingData = false;
    this.initialise();
    this.paneGettingData = false;
    this.showOverlay(false)
    this.IsBigIframeItem = false;
    this.IsSingleListItem = false;
    return;
}

/**
* Intialize wep pane dom elements
* 
*/ 
wep.initialise = function() {
	
    // Elements
    this.popup = document.getElementById('wep_popup');
    this.expandedContent = document.getElementById('wep_expandedContent');
    if(wep.isIE6()) {
        this.createIframe('wep_mask', this.popup);
        this.mask = document.getElementById('wep_mask');
    }
    this.createIframe('wep_expanderIframe', this.expandedContent);
    this.expanderPage = document.getElementById('wep_expanderpage');
    this.expanderPageScroller = document.getElementById('wep_expanderpagescroller');
    this.loading = document.getElementById('wep_loading');
    this.exppge = document.getElementById('wep_expanderpagecontent');
    this.expanderIframe = document.getElementById('wep_expanderIframe');
    this.fader = document.getElementById('wep_fader');
    this.leftborder  =document.getElementById('wep_leftborder');
    this.rightborder  =document.getElementById('wep_rightborder');	
    this.bottomborder  =document.getElementById('wep_bottomborder');
    this.buttonContainer =document.getElementById('wep_buttons');
	
	
    // Setting loading layer adjustment according to wep pane leyer size.
    this.loading.style.left = (this.expandedWidth / 2) - this.loadingIconSize +'px';
    this.loading.style.top = ( (this.expandedHeight / 2) - this.expanderPageScrollerTopMargin ) - this.loadingIconSize + 'px';
}

/**
* Resizing current wep pane layer according to generated  HTML container
* This method has very complex code because business requirement to provide
* @param {Boolean} Using scroll bar
*/ 
wep.reSize  = function(useScroll){

    var reSizedIframeWidth = (this.IsBigIframeItem ? (this.expandedWidth -  this.bigIframeWidthMargin) : this.expandedWidth);

    if(wep.isIE6()) {
        this.mask.style.marginLeft = this.expandedLeftMargin + 'px';
        this.mask.style.width = this.expandedWidth + this.expandedWidthMargin + (this.IsBigIframeItem ? 0 : this.expandedScrollWith) + 'px';
        this.mask.style.height = this.expandedHeight + this.expanderPageScrollerTopMargin + this.expanderPageScrollerBottomMargin + 'px';
    }

    if(this.IsSingleListItem) {
        this.expandedContent.style.marginLeft = this.expandedLeftMargin + (this.singleExpandedLeftMargin  * this.crntBtnNumber) + 'px';
    } 
    else {
        this.expandedContent.style.marginLeft = this.expandedLeftMargin + 'px';
    }

    this.expandedContent.style.width =  this.expandedWidth + this.expandedWidthMargin + (this.IsBigIframeItem ? 0 : this.expandedScrollWith) + 'px';
    this.expandedContent.style.height = this.expandedHeight + this.expanderPageScrollerTopMargin + this.expanderPageScrollerBottomMargin + 'px';

    this.leftborder.style.height  = parseInt(this.expandedContent.style.height) - 2 + 'px';
    this.rightborder.style.height  = parseInt(this.expandedContent.style.height) - 2 + 'px';

    this.expanderPageScroller.style.marginTop = this.expanderPageScrollerTopMargin + 'px';
    this.expanderPageScroller.style.height = this.expandedHeight + 'px';
    this.expanderPageScroller.style.width = this.expandedWidth + (this.IsBigIframeItem ? 0 : this.expandedScrollWith) + 'px';

    this.expanderPageScroller.style.overflow =  useScroll ? 'auto' : 'hidden';
    
    this.expanderIframe.style.marginTop = this.expanderPageScrollerTopMargin + 'px';
    this.expanderIframe.style.height = this.expandedHeight + 'px';
    this.expanderIframe.style.width = reSizedIframeWidth + 'px';
	
    this.bottomborder.style.width = (this.expandedWidth + this.expandedWidthMargin + (this.IsBigIframeItem ? 0 : this.expandedScrollWith)) - 10 + 'px';
	
    this.loading.style.left = (this.expandedWidth / 2) - this.loadingIconSize +'px';
    this.loading.style.top = ( (this.expandedHeight / 2) - this.expanderPageScrollerTopMargin ) - this.loadingIconSize + 'px';

    // Show wep pane layer
    this.showPane();
	
    // Show wep pane overlay
    this.showOverlay(true);
}


/**
* Get JSON Data
*/ 
wep.getJsonData = function() {
    if(!this.paneGettingData){
        this.paneGettingData = true;
			
        if(this.useCachedFeed)
        {
            var _cachedData = this.getCachedData(this.buttonId)
			
            if(_cachedData != null && _cachedData.id ==  this.buttonId)
            {
                // Load JSON data
                wep.pane(_cachedData)
                return;
            }

        } 
		
        var jsrOb = new jsr.JsonScriptRequest(this.paneServerUrl);
        jsrOb.buildScriptTag();
        jsrOb.addScriptTag();		
			
    }
}
		
		
/**
* This method is called by json service
* @param {Object} Feed JSON 
*/ 		
wep.pane = function(data) {
    		
    // Check data
    if(typeof(data) == 'undefined') return;
	
    if(this.useCachedFeed) {

        if(!this.isCachedItem(data.id))
        {
            // add new cache item
            this.addDataCache(data);
        }

    }
	
    if(this.lockWebPaneInit) return;
	
    // Load JSON data
    this.paneData = data;
	
    // Intialize Content
    this.createPaneLayer();

}

/**
* Replace iframe content 
* @param {Object} Iframe element 
* @param {String} URL 
* @param {String} Frame title 
*/ 	
wep.replaceIFrame = function(iframe, url, title){
    var newIFrame;
    var parent = iframe.parentNode;
    parent.removeChild(iframe);
    newIFrame = document.createElement("iframe");
    newIFrame.setAttribute("id", "wep_expanderIframe");
    newIFrame.setAttribute("frameBorder", "0");
    newIFrame.setAttribute("src", url);
    newIFrame.setAttribute("title", title);
    newIFrame.onload = function() {
        iframeLoaded = true;
    }
    parent.appendChild(newIFrame);
    this.expanderIframe = document.getElementById('wep_expanderIframe');
    this.expanderIframe.style.height = this.expandedHeight - 44 + 'px'
    this.expanderIframe.style.width = 855 + 'px'
}

/**
* Open new iframe layer with wep pane URL parameters
* @param {String} URL 
* @param {String} Frame title 
*/ 	
wep.getPageHtmlData = function(url,title){
    var separator = url.indexOf('?')>-1 ? '&' : '?';
    var params =  separator + 'wep_siteId=' + this.siteId + '&wep_buttonId=' + this.buttonId;
    this.replaceIFrame(this.expanderIframe, url + params, title);
    this.expanderIframe.src = url + params;
    this.expanderIframe.style.display = 'block';
    this.gettingData = false;
}

/**
* Open new iframe layer with wep pane URL parameters
* @param {Int} Width size 
* @param {Int} Height size  
* @param {Boolean} Use scroll bar
*/ 	
wep.setPaneSize = function(width,height,useScroll) { 

    // container size
    this.expandedWidth = width;
    this.expandedHeight = height;	

    // resize
    this.reSize(useScroll);
}


/**
* Create pane layer according to feed data types
*/ 	
wep.createPaneLayer = function() {

    // Local variables
    var exppge = document.getElementById('wep_expanderpagecontent');
    var pgecont = '';
    var items = this.paneData.feed;
    var item;
    var maxRowCount = this.paneData.max_rows == null ?  0  :  this.paneData.max_rows;
    var subItemCount = this.paneData.max_sub_items == null ?  7  :  this.paneData.max_sub_items;
    var moreText =  this.paneData.more_text == null ?  'More'  :  this.paneData.more_text;
    var child;	
    var cat;	
    var singleCol;
    var isSSL = false;
    var separator;
    var linkTarget;
    var columnCount = this.paneData.num_of_columns == null ? this.defaultColumnCount : this.paneData.num_of_columns;
    var rowCount = 1;
    var catUrl;
    var protCatUrl;
    var trackingUrl;
    var categoryId;
    var feedIframeWidth;
    var feedIframeHegiht;	
    var useScrollBar = false;
    var IsPoruducts = (wep.currButtonType) == 'Products' ? true : false;
    var IsList = true;
	
    // Is SSL
    if(this.feedDomainTBN.slice(0, 8) == "https://" || this.feedDomainFNP.slice(0, 8) == "https://") isSSL = true;

    // Hide mask iframe visibility
    this.expanderIframe.style.display = 'none';	

    // Calculating the number of column count with behavior formula
    if(items.length <= 12 && this.paneData.num_of_columns == null)
    {
        columnCount = this.getSizeBehaviorFormula(items.length);
    }

    // Checking display type
    if(items.length == 1)
    {
        // Is list
        IsList =  (items[0].iframe_link != null) ? false : true; 
				
        // Setting big iframe size according to feed parameters
        feedIframeWidth =  (items[0].iframe_width != null) ? items[0].iframe_width : this.bigIframeWidth; 
        feedIframeHegiht =  (items[0].iframe_height != null) ? items[0].iframe_height : this.bigIframeHeight; 	
				
    } else {
        IsList = true;
    }

    // Is big iframe item
    this.IsBigIframeItem = IsList ? false : true;
			
    // Is single list item
    this.IsSingleListItem = (items.length == 1 || (this.paneData.num_of_columns == 1)) && IsList
		
    // Generate pane  HTML according to type of feed's item
    if(IsList)
    {
        //  Content  html  buldier begin
        pgecont = '<div class="web-pane-portlets clearfix" id="web-pane-portlets" >';

        for (var I = 0 ; I < items.length ; I++) {
					
            item = items[I];
					
            categoryId = item.id
					
            // Create wrapper division with item index
            if(I % columnCount==0) pgecont += '<div class="clearfix row-spearator">';
				
            // Teaser begin
            pgecont +=	this.createTeaserItems(item,items,I,columnCount,catUrl,categoryId,subItemCount,moreText)
            // Teaser end 
					
            // Close wrapper division
            if(I % columnCount==(columnCount-1)) pgecont += '</div>';	
													
            rowCount++;
					
        }
			
        pgecont += '</div>';
			
		
    } else
// Pane Type Iframe 
{
        // Create iframe in teaser  container 
        this.createTeaserIframe(items[0],catUrl,protCatUrl,isSSL)
					
    }

    //  Content  html  buldier end

    // Insert HTML
    this.setExpanderPage(pgecont);

    // Calculating the container size  (resize functionality) begin
	
    if(IsList)
    {
        if(items.length < this.defaultColumnCount)
        {
            columnCount = items.length;
        }
			
        // Calculate & resize pane
        this.calculatePaneSize(items,columnCount,maxRowCount,useScrollBar);

    }else {
			
        wep.setPaneSize(feedIframeWidth,feedIframeHegiht,true);
    }
		
    // Calculating the container size  (resize functionality) end		
	
	
    // Show web pane layer & define global variables
    //this.loading.style.display = 'none';
	
    if(this.show)exppge.style.visibility = 'inherit';
    if(this.buttonNum != null)this.selectButton(this.buttonNum);
	
    this.show=true;
    this.gettingData = false;
    this.paneGettingData = false;
	
}

/**
* Calculating wep pane container size with teaser count and container sizes
* @param {Object} Item (Feed Row) 
* @param {Int} Column count
* @param {Int} Maximum row count
* @param {Boolean} Use  scroll bar 
*/ 	
wep.calculatePaneSize  = function(items,columnCount,maxRowCount,useScrollBar){
	
    // (N / Column Count) + (N % Column Count) == 0 ? 0:1
    var _rowCount =  (items.length / columnCount) +  ((items.length % columnCount == 0) ? 0 : 1)
	
    if(_rowCount >  maxRowCount && maxRowCount != 0 )
    {
        _rowCount =  maxRowCount;
    }

    // Calculation with default size
    var _ctnH =  parseInt(this.teaserItemHeight * _rowCount);
    var _ctnW =  (this.teaserItemWidth * columnCount);

    // Set container size
    wep.setPaneSize(_ctnW,_ctnH,useScrollBar);
	
    // calculation with content size
    var _ctnHContent =  this.getTeaserRowSize(parseInt(this.teaserItemHeight * _rowCount),_rowCount);
	

    useScrollBar = ((_rowCount * columnCount) < items.length);
				
    // Set container size
    wep.setPaneSize(_ctnW,_ctnHContent,useScrollBar);	
	
}

/**
* Create iframe element in teaser
* @param {Object} Item (Feed Row) 
* @param {String} Category URL
* @param {String} Category URL with SSL protocol
* @param {Boolean} Is SSL
*/ 	
wep.createTeaserIframe = function(item,catUrl,protCatUrl,isSSL){

    if(item.iframe_link != null)
    {
        catUrl = item.iframe_link.href;
			
        protCatUrl = isSSL ? catUrl.replace('http://', 'https://') : catUrl;
			
        wep.getPageHtmlData(protCatUrl, item.title != null ? item.title : '')
    }
}

/**
* Create taser items
* @param {Object} Item (Feed Row) 
* @param {Object} Feed list
* @param {Int} Loop index
* @param {Object} Omniture tracking code
* @param {String} Category URL
* @param {String} Category ID
* @param {Int} Maximum sub item count
* @param {String} More text localization
* @return Generated teaser HTML
*/ 	
wep.createTeaserItems = function(item,items,I,columnCount,catUrl,categoryId,subItemCount,moreText){
    var isSSL = false;
    if (document.location.href.slice(0,6) == 'https:') {
        isSSL = true;
    }
    var btnType = this.buttonFeed[this.crntBtnNumber].type;
    var trackingCode = 'omnitureWEPPaneClick(\''+ btnType +'\',\'' + item.id + '\',\'' + item.title + '\')" ';

    var pgecont = '';	

    // Teaser HTML Begin
    pgecont += '<div class="portlets-teaser '+ this.getTeaserType(item) +  ((I % columnCount==(columnCount-1)) ? ' column-end' : '')  + ' clearfix">';
	
    // Type iframe 
    if(item.iframe_link != null)	
    {												 	
        pgecont += this.getTeaserIframe(item,items[I],I,this.smallIframeWidth,this.smallIframeHeigh);			
    }
	
    // Type teaser
    else
    {
        // Teaser image
        if(item.img != null && item.img.src != '')
        {
			
            var imgUrl = item.img.src;
            if(isSSL) {
                imgUrl = imgUrl.replace("http://","https://")
                }

            pgecont += '<div class="teaser-media">';
            pgecont += '<img width="60" height="60" border="0" alt="' + ((item.title != null) ? item.title : '')  + '" src="'+ imgUrl +'" ';
			
            // teaser category link
            if(item.link != null && item.title != null){
            	var ubertagParam= 'wep_landing';
				if((item.link.href).indexOf('?')>0){
					ubertagParam= '&'+ubertagParam;
				}else{
					ubertagParam= '?'+ubertagParam;
				}
                pgecont += ' onclick="wep.openUrl(\'' + item.link.href +'\',\'' + (item.link.target != null ?  item.link.target : '')  + '\'); ';
                pgecont += trackingCode;
                pgecont += 'class="link"';
            }
			
            pgecont += '/>';
            pgecont += '</div>';
        }
		
        pgecont += '<div class="teaser-content">';
		
        // Teaser title & cartegory & category link
        if(item.link != null && item.title != null){
        		var ubertagParam= 'wep_landing';
				if((item.link.href).indexOf('?')>0){
					ubertagParam= '&'+ubertagParam;
				}else{
					ubertagParam= '?'+ubertagParam;
				}
            linkTarget = item.link.target != null ? "target='"+ item.link.target +"'" : "";
				
            pgecont += '<h2><a href="'+ item.link.href +'"  '+linkTarget+' title="'+ item.title +'" ';
            pgecont += ' onclick="';
            pgecont += trackingCode;
            pgecont += '>'+ item.title +'</a></h2>'; 
				
        } else {
            pgecont +=  (item.title != null && item.title != '') ? '<h2>' +  item.title  + '</h2>' : '';	
        }

        // Teaser description
        if(item.link != null && item.description != null && item.description != '') {
        	var ubertagParam= 'wep_landing';
				if(item.link.href !=null & (item.link.href).indexOf('?')>0){
					ubertagParam= '&'+ubertagParam;
				}else{
					ubertagParam= '?'+ubertagParam;
				}
            pgecont += '<p><a href="'+ item.link.href + '"  '+linkTarget+' title="'+ item.title +'" ';
            pgecont += ' onclick="'; 
            pgecont += trackingCode;
            pgecont += '>'+ item.description +'</a></p>';
        }
        else if(item.description != null && item.description != '') {
            pgecont += '<p>'+ item.description +'</p>';
        }
        else {
            pgecont += '';
        }
			
        // Teaser sub items link
        if(item.children != null && item.children.length > 0)
        {
            pgecont +=  this.createSubItems(item,catUrl,categoryId,subItemCount,moreText,btnType,trackingCode);
        }
			
        pgecont += '</div>';
		
    } 	
	
    pgecont += '</div>';
    // Teaser HTML End
	
    return pgecont;
}

/**
* Create sub items HTML
* @param {Object} Item (Feed Row) 
* @param {String} Category URL
* @param {Int} Maximum sub item count
* @param {String} More text localization
* @return Generated sub items HTML
*/ 	
wep.createSubItems = function(item,catUrl,categoryId,subItemCount,moreText,btnType,trackingCode){

    var pgecont = '';
	
    var _textVisible = false;
    pgecont += '<ul>';
    for (var C = 0 ; C < item.children.length ; C++) {
			
        child = item.children[C];
        linkTarget = child.link.target != null ? "target='"+ child.link.target +"'" : "";
        linkTargets = child.link.target != null ? child.link.target : "";
        linkHref = child.link.href != null ? child.link.href : "javascript:void(0);"

        var childTrackingCode = 'omnitureWEPPaneClick(\''+ btnType +'\',\'' + child.id + '\',\'' + child.title + '\')" ';

        if(C < subItemCount)
        {
        	var ubertagParam= 'wep_landing';
				if(linkHref !=null & linkHref.indexOf('?')>0){
					ubertagParam= '&'+ubertagParam;
				}else{
					ubertagParam= '?'+ubertagParam;
				}
            pgecont += '<li><a href="'+ linkHref + '"  '+linkTarget+' title="'+ child.title +'"';
            pgecont += ' onclick="';
            pgecont += childTrackingCode;
            pgecont += '>'+ child.title +'</a></li>'; 
				
        } else {	
				
            if(!_textVisible)
            {
            	var ubertagParam= 'wep_landing';
				if(item.link.href !=null & (item.link.href).indexOf('?')>0){
					ubertagParam= '&'+ubertagParam;
				}else{
					ubertagParam= '?'+ubertagParam;
				}
                pgecont += '<li class="more"><a href="'+  item.link.href + '"  title="'+ moreText +'"';
                pgecont += ' onclick="'
                pgecont += trackingCode;
                pgecont += '>'+ moreText +'</a></li>';
                _textVisible = true;
            }
        }
			
    }
    pgecont += '</ul>';		


    return pgecont;
}


/**
* Get column count according to behavior formula
* @param {Int} Current feed geerow count
* @return column count
*/ 	
wep.getSizeBehaviorFormula = function(length){
    return (length % 4 == 1) ? 3 : 4;
}

/**
* Get teaser row size according to wrapper container
* @param {Int} Calculated teaser container height
* @param {Int} Row count
* @return recalculated teser  container height
*/ 	
wep.getTeaserRowSize = function(size,rowCount){
	
    var _ret = 0;
    var _count = 0;
    var _container = document.getElementById('web-pane-portlets')
    var _list = null;
	
    if(_container != null)
    {	
        _list =  _container.getElementsByTagName('div');
			
        if(_list != null && _list.length > 0)
        {
            for (var I = 0 ; I < _list.length ; I++) {
                if(_list[I].className == 'clearfix row-spearator')
                {
                    if(rowCount > _count)
                    {	
                        _ret += parseInt(_list[I].offsetHeight);
                        _count++;
                    }
                }
            }
        }
		
    }
		
    return _ret == 0 ?  size : _ret;

}


/**
* Get teaser type according to feed propertie
* @param {Object} Item (Feed Row) 
* @return type of teaser
*/ 	
wep.getTeaserType = function(feed){
	
    var type = '';
	
    if(feed.img != null) {
        type = 'type-1'
    };
    if(feed.img != null && feed.title != null) {
        type = 'type-2'
    };
    if(feed.img != null && feed.title != null && feed.description != null) {
        type = 'type-3'
    };
    if(feed.img != null && feed.title != null && feed.children != null) {
        type = 'type-4'
    };	
	
    if(feed.iframe_link != null) {
        type = 'type-5 iframe'
    };

    return type;
	
}

/**
* Get teaser inner iframe
* @param {Object} Item (Feed Row) 
* @param {Object} Feed
* @param {Int} Loop Index
* @param {Int} Ifarame width 
* @param {Int} Ifarame height 
* @return iframe HTML element
*/ 	
wep.getTeaserIframe = function(item,feed,count,width,height){
		
    var _width = (feed.iframe_width != null) ? feed.iframe_width : width ;
    var _height = (feed.iframe_height != null) ? feed.iframe_height : height;
	
    var strIframe = "<iframe ";

    strIframe += ' id = "teaser-iframe-'+count+'"';
    strIframe += ' frameBorder = "0"';
    strIframe += ' style = "width: '+ _width +'px;height: '+ _height +'px"';
	
    if(item.iframe_link != null ) 	strIframe += 'src = "'+		item.iframe_link.href +'"';
    if(item.title != null ) 		strIframe += 'title = "'+	item.title +'"';
	
    strIframe += "></iframe >";

    return strIframe;
}


/**
* Clear wep pane content
*/ 	
wep.clearExpanderPage = function(){
    this.exppge.innerHTML = ''; 
}

/**
* Set wep pane content
* @param {String} Wep pane content HTML
*/ 	
wep.setExpanderPage = function(str){
    this.exppge.innerHTML = str; 
}

/**
* Show menu (Menu button event)
* @param {Int} Button ID
* @param {Int} Button Number
* @param {String} Button Type
*/ 	
wep.showmenu = function(btnId, btnNum, btnType){
	
    this.buttonNum = btnNum;
	
    this.paneServerUrl = this.feedDomainFNP + '/fnp/' + btnId + '/' + this.locale.replace('_', '/') + '/';
    if(!this.paneGettingData){
        this.crntBtnNumber = this.getButtonNum(btnType);
        this.currButtonType = btnType;
        if(this.currentBtn != btnId && this.currentBtn !== ''){
            this.expanderIframe.style.display = 'none';	
            this.currentBtn = btnId;
            this.buttonId = btnId;
            this.exppge.innerHTML = '';
            this.loading.style.display = 'block';
            this.getJsonData();
            this.gettingData = true;	
        }
        else{
            if(this.currentBtn == btnId){
                // already open
					
                this.buttonId = btnId
            }
            else{
                // init 
                this.currentBtn = btnId; 
                this.buttonId = btnId
                this.getJsonData();
                this.gettingData = true;
            }
        }
		
    }
	
	


}

/**
* Show overlay
* @param {boolean} overlay visibility
*/ 	
wep.showOverlay = function(darken){
    var overrideDocHeight
    overrideDocHeight = true;
    var styleObj = document.createElement("style");
    if(overrideDocHeight){
        document.body.style.height='auto';
        if(navigator.userAgent.indexOf('IE') == -1){
            styleObj.setAttribute("type", "text/css");
            try{
                styleObj.innerHTML='html,body{height:auto;}';
            }catch(e){};
            document.getElementsByTagName("head").item(0).appendChild(styleObj);
        }
    }
	
    // Resize overlay sizes  according to windows size
    this.resizeOverlay();
	
    if(darken){
        this.fader.style.display = 'inline';
    }
    else{
        this.fader.style.display = 'none';
        if(overrideDocHeight){
            document.body.style.height='100%';
            if(navigator.userAgent.indexOf('IE') == -1){
                styleObj.setAttribute("type", "text/css");
                try{
                    styleObj.innerHTML='html,body{height:100%;}'
                    }catch(e){};
                document.getElementsByTagName("head").item(0).appendChild(styleObj);
            }
        }
    }
}

/**
* Resize overlay
*/ 
wep.resizeOverlay = function(){
    var pageHeight = document.documentElement.clientHeight;
    if (navigator.appName.indexOf("Microsoft")==-1) pageHeight = document.documentElement.scrollHeight;
    var faderHeight = pageHeight;
    var windowHeight = 0;
    var offset;
    var topBar = document.getElementById('topbar');
    var topBarClass = topBar.className;

    if(topBarClass.indexOf('wepType2') > 0) {
        offset = 105;
    }
    else {
        offset = 69;
    }
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName.indexOf("Microsoft")==-1) {
            windowHeight = window.innerHeight;
      
        }
        else {
            windowHeight = document.body.offsetHeight;
      
        }
    }
    if(pageHeight < windowHeight) faderHeight = windowHeight;
    wep.fader.style.height = faderHeight - offset + 'px';      
}


/**
* Select to button
* @param {Int} Button ID
*/ 
wep.selectButton = function(buttonId){
    var item;
    for(var i=0; i<this.numButtons; i++){
        item = document.getElementById('wep_button' + i);
		
        if(i==parseInt(buttonId)){
            item.className = 'wep_buttonSelected' + ((item.rel == 'active') ? ' wep_buttonSelected_active' :'');
        }
        else {
            item.className = 'wep_button' + ((item.rel == 'active') ? ' active' :'');
        }
		
    }
}




/**
* Open new URL
* @param {String} URL
* @param {String} Window Target
*/ 
wep.openUrl = function(url,target){
	
    if(url == null) return;
	
    target=='blank' ? window.open(url) : document.location.href=url;
}

/**
* Create new iframe  element
* @param {Int} ID of element
* @param {Object} Parent element
*/ 
wep.createIframe = function(id, parent){
    var newIFrame;
    if(!document.getElementById(id)){
        newIFrame = document.createElement("iframe");
        newIFrame.setAttribute("id", id);
        newIFrame.setAttribute("frameBorder", "0");
        //newIFrame.setAttribute("src", this.blankPageUrl);
        //To prevent 'This Page Contains Both Secure and Non-Secure Items' Error Message
        //http://support.microsoft.com/kb/184960
        newIFrame.setAttribute("src", "javascript:void(0)");
        parent.appendChild(newIFrame);
        
    }
}


/**
* Open Pane area
* @param {String} Button Id
*/ 
wep.openPane = function(btnType){
    if (!btnType) {
        btnType = "Shop";
    }
    window.scrollTo(0, 0);
    this.mouseIsOver = false;
    var btnId = this.getButtonId(btnType);
    var btnNum = this.getButtonNum(btnType);
      
    setTimeout(
        function() {
            try {
                wep.menudelay(btnId, btnNum, btnType);
            }
            catch(e){}
                  
            try {
                wep.hoverButton();
            }
            catch(e){}
        },
        100
        );
}


/**
* Get button ID by button type
* @param {String} Button Type
*/ 
wep.getButtonId = function(buttonType){
    for(var i=0;i<this.btnAry.length;i++){
        if(this.btnAry[i][1]==buttonType)
            return this.btnAry[i][0];
    }   
}
/**
* Get button number by button type
* @param {String} Button Type
*/ 
wep.getButtonNum = function(buttonType){
    for(var i=0;i<this.btnAry.length;i++){
        if(this.btnAry[i][1]==buttonType)
            return i;
    }   
}

wep.intersection = function (a,b) {
    var result = [];
    if (a != null && b != null) {
        for (var i = 0; i < a.length; i++) {
            for (var j = 0; j < b.length; j++) {
                if (a[i] === b[j])
                    result.push(a[i]);
            }
        }
    }
    return result;
}

wep.isArrayNotEmpty = function (arr) {
    return arr != null && arr.length > 0;
}

wep.isIE6 = function() {
    if(navigator.userAgent.indexOf('MSIE 6.0') != -1) {
        return true;
    }
    else {
        return false;
    }
}

function reloadAccessibleIframe(iframeId,buttonId){
    if(this.wep.currentButtonType == 'Shop'){
        var isSSL = false;
        if(this.wep.feedDomainTBN.slice(0, 8) == "https://" || this.wep.feedDomainFNP.slice(0, 8) == "https://") 
            isSSL = true; 
		
        var iframe = document.getElementById(iframeId)
        var iframe_url = iframe.src;
        iframe_url = isSSL ? iframe_url.replace('http://', 'https://') : iframe_url;
        var separator = iframe_url.indexOf('?')>-1 ? '&' : '?';
        var params =  separator + 'wep_siteId=' + this.wep.siteId + '&wep_buttonId=' + buttonId;
        iframe_url = iframe_url + params;
        iframe.src = iframe_url;
    }
	 
}

/*****************/
/* WEP FUNCTIONS */
/*****************/

jQuery(document).ready(function(){

    // News Ticker
    var newsTicker = function (obj,timer) {
        var obj = jQuery(obj);
        if(obj.length != 0) {
            var Interval;
            var ticker_display_flag= 1;
            obj.init = function(){
				
                obj.before('<a href="javascript:;" id="wepStoreMessageCollapseBtn">[-]</a>');
					
                jQuery('a#wepStoreMessageCollapseBtn').bind('click', function(e){
                    e.preventDefault();
                    if(ticker_display_flag)	{
                        obj.css('visibility','hidden');
                        jQuery(this).html('[+]');
                        jQuery(this).addClass("collapsed");
                        ticker_display_flag = 0;
                        clearTimeout(Interval);
                    }
                    else {
                        obj.css('visibility','visible');
                        jQuery(this).html('[-]');
                        jQuery(this).removeClass("collapsed");
                        ticker_display_flag = 1;
                        Interval = setInterval(function() {
                            obj.startAnimate()
                            },timer);
                    }
                });	
				
                obj.find("li:first").addClass("active");
                jQuery(this).find("li:last").addClass("last");
                Interval = setInterval(function() {
                    obj.startAnimate()
                    },timer);
                obj.find("li").bind("mouseover", function() {
                    obj.stopAnimate();
                });
                obj.find("li").bind("mouseout", function() {
                    Interval = setInterval(function() {
                        obj.startAnimate()
                        },timer);
                });
            };
            obj.stopAnimate = function() {
                clearInterval(Interval);
            };
            obj.startAnimate = function() {
                var ActiveElement = obj.find("li.active");
                var class_name =  ActiveElement.attr("class");
                ActiveElement.fadeOut("slow", function() {
                    if (class_name == "last active") {
                        jQuery(this).removeClass("active").parent().find("li:first").fadeIn("slow").addClass("active");
                    }
                    else {
                        jQuery(this).removeClass("active").next().fadeIn("slow").addClass("active");
                    }
                });
            };
            obj.init();
        };	
		
    }
    var webBarNewsTicker = new newsTicker("ul#wepNewsRotator",(wep.newsTickerDelayTime != null) ? wep.newsTickerDelayTime : 3000);
	
    // Country Language Selection
    var _t;
    if(jQuery('div.wepLanguage').length != 0) {
        jQuery('ul.wepCountryBtnWrap > li:first-child').hover(
            function() {
                _t = setTimeout(function() {
                    jQuery('ul#wepCountriesContainer').css("visibility","visible");								
                },400) 
				
            },
            function() {
                clearTimeout(_t);
                jQuery('ul#wepCountriesContainer').css("visibility","hidden");
            }
            )	
    }
})