/** 
*@projectDescription Look Book - a visual design surface for creating outfits and room collections 
*@author  Howard van Rooijen - howard.vanrooijen@conchango.com
*@version 1.0
*@version 1.1 - Re-instate Coremetric tagging for the LookBook.
*/


/** 
* Encapsulates all the logic for creating and integrating the Flash Look Book with the Oli site.
* @classDescription Encapsulates all the logic for creating and integrating the Flash Look Book
* with the Oli site.
* @constructor
* @return {Object}  Returns a new Look Book object.
*/
function LookBook() 
{
    LookBook.prototype.Initialise()
};

/**
 * Adds a product to the Look Book via the flash external interface. The following attributes are extracted from the DIV:
 * an, a, n, an, nu, ns.
 * @method
 * @alias AddProductToLookBook
 * @alias LookBook.AddProductToLookBook
 * @param {HTMLDivElement} item the HTMLDivElement that has product information embedded via HTML expando properties
 */
LookBook.prototype.AddProductToLookBook = function(item) {
    var version = deconcept.SWFObjectUtil.getPlayerVersion();

    if (version["major"] < 6) {
        alert("You need the Adobe Flash Plug-in installed to use the Oli look book.\nPlease click the \"Install\" button below to get the Plug-in.")
    }
    else if ((version["major"] > 6) && (version["major"] < 8)) {
        alert("You need upgrade the currently installed version the Adobe Flash Plug-in to use the Oli look book.\nPlease click the \"Upgrade\" button below to get the Plug-in.")
    }
    else {
        var product = new Product(
              item.getAttribute("an"),
              item.getAttribute("a"),
              item.getAttribute("n"),
              item.getAttribute("au"),
              item.getAttribute("nu"),
              item.getAttribute("ns"));

        flashObject = document.LookBookFlash;

        flashObject.AddProductToLookBook(product.a);

        //Perform Core metrics call
        try {
            cmCreatePageviewTag("AddProduct:" + product.a, "LookBook", "", "");
        }
        catch (e) {
        }
    }
};

/**
 * variable to hold lookbook loaded state
 */
LOOKBOOK_LOADED = false;

/**
 * LookBook Mode Constants
 *
 **/
LookBook.MINI = 1; //just the bar
LookBook.MIDI = 2; //the bar and the dock
LookBook.MAXI = 3; //the bar the dock and the canvas
LookBook.RESET = 4;//resets to saved mini or midi state

/**
 * Change the LookBook mode. The mode control which elements are displayed, possible modes are:
 *
 * mini - just the bar
 * midi - bar and bock
 * maxi - bar, doc and canvas area (full size)
 * reset- reset to saved mini or midi
 *
 * @method
 * @param {Integer} mode, values see LookBook Mode Constants.
 */
LookBook.prototype.SetMode = function(mode)
{
    if (mode < 1 | mode > 4)
    {
        alert("LookBook.prototype.SetLookBookMode called with an invalide value for mode.\nValid values are LookBook.MINI, LookBook.MIDI, LookBook.MAXI or LookBook.RESET");
    }
    else
    {
        flashObject = document.LookBookFlash;
	if(LOOKBOOK_LOADED)
        {
            flashObject.SetMode(mode);
        }
    }
};

/**
 * Creates and inserts a new HTMLDivElement into the pages DOM, this is used as an overlay layer which greys out
 * the Oli site beneath. A second layer is inserted inside the overlay to contain the flash object.
 * @method
 * @alias CreateLookBookOverlay
 * @alias LookBook.CreateLookBookOverlay
 */
LookBook.prototype.CreateLookBookOverlay = function()
{
  var ie6Style = "";

  if (LookBook.prototype.GetInternetExplorerVersion() == 6)
  {
    LookBook.prototype.CreateLookBookOverlayForIE6();
    
    $("#lookBookFrame").after("<div id=\"LookBookOverlay\" style=\"position:absolute;bottom:-1px;left:-16px;height:25px;width:100%;z-index:1000;\"/>");
    ie6Style = " style=\"padding-left:15px;margin-left:0px;\"";
  }
  else
  {
    $("<div id=\"LookBookOverlay\"/>").appendTo("body");
  }

  $("<div id=\"LookBookViewPort\"" + ie6Style + "></div>").appendTo("#LookBookOverlay");

  var version = deconcept.SWFObjectUtil.getPlayerVersion();
  
  if (version["major"] < 6)
  {
    $("<img id=\"\installFlash\" alt=\"Install Adobe Flash\" src=\"" + lookBookServerUrl + "LookBook/Images/noFlash.gif\"/>").appendTo("#LookBookViewPort");
    
    $("#installFlash").click(function(){LookBook.prototype.InstallFlash();return false; });
  }
  else if ((version["major"] >= 6) && (version["major"] < 8))
  {
    $("<img id=\"\installFlash\" alt=\"Update Adobe Flash\" src=\"" + lookBookServerUrl + "LookBook/Images/updateFlash.gif\"/>").appendTo("#LookBookViewPort");
    $("#installFlash").click(function(){LookBook.prototype.UpdateFlash();return false; });
  }
  else
  {
    var so = new SWFObject(lookBookServerUrl + "LookBook/Flash/lookBook.swf", "LookBookFlash", "992", "600", "8", "#ffffff");
    so.useExpressInstall(lookBookServerUrl + 'LookBook/Flash/expressinstall.swf');
    so.addParam("wmode", "transparent");
    so.write("LookBookViewPort"); 
  }
};

/**
 * Resolved issue where loading of the LookBook affects the downloading of some product images
 * delays the loading of the LookBook to allow DOM Image events to be fired.
 * @method
 * @alias CreateLookBookOverlayDelayedLoading
 * @alias LookBook.CreateLookBookOverlayDelayedLoading
 */
LookBook.prototype.CreateLookBookOverlayDelayedLoading = function()
{
	setTimeout("LookBook.prototype.CreateLookBookOverlay()", 500);	
}

/**
 * Alternative rendering strategy for IE 6 to position the LookBook dockbar at the bottom of the page
 * @method
 * @alias CreateLookBookOverlayForIE6
 * @alias LookBook.CreateLookBookOverlayForIE6
 */
LookBook.prototype.CreateLookBookOverlayForIE6 = function()
{
  $("BODY").css({overflow: "hidden", height:"100%", width: "100%", margin:"0px"});
  $("#divPage").wrap("<div id='lookBookFrame' style='overflow:auto;height:100%;position:relative;height:100%;width:100%'></div>");
  //There is an additional call, serverside (lookBook.RenderBodyTagAttributesForIE6()) to add the scroll="no" attribute to the HTML BODY tag
};

/**
 * Inspects the pages DOM for the products (contained within a productGrid element) and inserts
 * the "Add to Look Book" button and JavaScript events required to add the product date to the Look Book
 * flash object.
 * @method
 * @alias FindLookBookProducts
 * @alias LookBook.FindLookBookProducts
 */
LookBook.prototype.FindLookBookProducts = function() {
    $("ul.productGrid li h4").each(function(i) {

        if ($(this).parent().find("a.buttonView")[0] == null) {
            return;
        }

        var title = $(this).parent().find("a.buttonView").attr("title");

        var items = $(this).parent().find("a.buttonView")[0].href.split('?')[1].split('&');

        var button = $("<span class=\"buttonLookBook\">Add to Look Book</span>")

        for (var i = 0; i < items.length; i++) {
            var par = items[i].split('=');
            button[0].setAttribute(par[0], par[1]);
        }

        button.click(function() { LookBook.prototype.AddProductToLookBook(this); ShowAddedToLookBook(title); return false; });

        if ($.browser.msie) {
            button[0].style.cursor = "hand";
        }
        else {
            button[0].style.cursor = "pointer";
        }

        // RJS Changed - was $(this).next().after(button);
        $(this).next().next().after(button);
    });
};

function ShowAddedToLookBook(name) 
{   
    $("#AddedToLookBookHeader").text(name)
    
    //LookBook.prototype.SetMode(LookBook.MAXI);
    var url = "#TB_inline?height=250&width=400&inlineId=AddedToLookBookContainer&modal=true";
    tb_show("", url);

}


/**
 * Returns the version number of internet explorer. Used to for alternative rendering strategy
 * @method
 * @alias GetInternetExplorerVersion
 * @alias LookBook.GetInternetExplorerVersion
 */
LookBook.prototype.GetInternetExplorerVersion = function()
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

/**
 * Cross Browser function for obtaining the current Scroll Y value
 * @alias getScrollY
 * @alias LookBook.getScrollY
 * @return {string} Returns the current Scroll Y value as a CSS height value - i.e. "10px". 
 */
LookBook.prototype.getScrollY = function()  
{ 
    var scrollY = 0;
    if( document.documentElement && document.documentElement.scrollTop ) {
        scrollY = document.documentElement.scrollTop;
    }
    else if( document.body && document.body.scrollTop ) {
        scrollY = document.body.scrollTop;
    }
    else if( window.pageYOffset ) {
        scrollY = window.pageYOffset;
    }
    else if( window.scrollY ) {
        scrollY = window.scrollY;
    }
     
    return scrollY;
};

/** 
* Workaround for the fact that IE doesn't seem to pick up on the Window.OnResize event - this may have
* something to do with the overflow:hidden style on the HTML Body tag.
* @method
* @alias IEOnResize
* @alias LookBook.IEOnResize
*/
LookBook.prototype.IEOnResize = function()
{
  if ((previousClientHeight != document.documentElement.clientHeight) || (previousClientWidth != document.documentElement.clientWidth))
  {
    LookBook.prototype.ResizeDock();
  }
  
  previousClientHeight = document.documentElement.clientHeight;
  previousClientWidth = document.documentElement.clientWidth;
};

/**
 * Inserts an external CSS file into the current pages DOM
 * @method
 * @alias IncludeCSS
 * @alias LookBook.IncludeCSS
 * @param {String} The url to the CSS file to be included in the page's DOM
 */
LookBook.prototype.IncludeCSS = function(file)
{
    var link = document.createElement('link');
    link.rel = "stylesheet";
    link.type = 'text/css';
    link.href = file;
   
    document.getElementsByTagName('head').item(0).appendChild(link);
}

/**
 * Inserts an external JavaScript file into the current pages DOM
 * @method
 * @alias IncludeScript
 * @alias LookBook.IncludeScript
 * @param {String} The url to the JavaScript file to be included in the page's DOM
 */
LookBook.prototype.IncludeScript = function(file)
{
  var script = document.createElement('script');
  script.src = file;
  script.type = 'text/javascript';
  script.defer = true;

  document.getElementsByTagName('head').item(0).appendChild(script); 
};


/** 
* Creates and adds in all the required files for the Look Book to work correctly
* and hooks up to the relevent scroll and resize events to maintain the position of the dock bar.
* @method
* @alias Initialise
* @alias LookBook.Initialise
*/
LookBook.prototype.Initialise = function()
{
  this.IncludeScript(lookBookServerUrl + "LookBook/Scripts/swfobject.js"); //js library used for embedding the flash object
  this.IncludeScript(lookBookServerUrl + "LookBook/Scripts/Product.js"); //js data transfer object for product information
  this.IncludeCSS(lookBookServerUrl + "LookBook/Styles/LookBook.css"); //style for the Look Book Layers

  $(document).ready(this.FindLookBookProducts); //add the "Add to Look Book" button to each product
  $(window).load(this.CreateLookBookOverlayDelayedLoading); //create the grey overlay layer

  //There doesn't seem to be a cross browser way of capturing the window resize event so we have IE and FF workarounds
  if (LookBook.prototype.GetInternetExplorerVersion() <= 7)
  {
    previousClientHeight = document.documentElement.clientHeight;
    previousClientWidth = document.documentElement.clientWidth;
  
    setInterval("LookBook.prototype.IEOnResize();", 500);
  }
  else
  {
    window.onresize = function() { LookBook.prototype.ResizeDock() };
  }
};

/**
 * Control the UI so that the user can install Flash
 * @method
 * @alias InstallFlash
 * @alias LookBook.InstallFlash
 */
LookBook.prototype.InstallFlash = function()
{
  window.open('http://www.adobe.com/go/getflashplayer','GetFlash','width=1024,height=768,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
};

/**
 * Loads Look Book data (from remote user) into the Flash Object
 * @method
 * @alias LoadLookBook
 * @alias LookBook.LoadLookBook
 * @param {String} Look Book data containing product Id, position and size - i.e. 22X621_12,500,300,2,75,100|22X872_12,500,300,2,75,100| 
 */
LookBook.prototype.LoadLookBook = function(lookBookData)
{
  flashObject = document.LookBookFlash;
  flashObject.LoadLookBookData(lookBookData);
  // After this point the lookbook should be fully loaded and its exposed methods callable
  LOOKBOOK_LOADED = true;
};

/** 
* Resizes the Look Book when the browser window resizes
* @alias setDockPosition
* @alias LookBook.setDockPosition
*/
LookBook.prototype.ResizeDock = function()
{
  var dockHeight = parseInt($("#LookBookOverlay").css('height'.replace('px','')));
  
  if (dockHeight > 105)
  {
    $("#LookBookOverlay").css('height', document.documentElement.clientHeight);
    
    try
    {
      flashObject = document.LookBookFlash;
      flashObject.height= document.documentElement.clientHeight;
    }
    catch(exception) {}
  }
};

/** 
* Method called by the Look Book when it has initialised and wants to load it's data.
* This is used to load a remote user's collection via the "send to a friend" functionality
* @method
* @alias RetrieveLookBookData
* @alias LookBook.RetrieveLookBookData
*/
LookBook.prototype.RetrieveLookBookData = function()
{
    try
    {
        var lookBookData = new Array();

        lookBookData[0] = lookBookSharedData;
        lookBookData[1] = lookBookProductServiceUrl;
        lookBookData[2] = lookBookShareServiceUrl;
        lookBookData[3] = lookBookBasketServiceUrl;
        lookBookData[4] = lookBookSharedLandingPageUrl;
        lookBookData[5] = lookBookSendToFriendLandingImageUrl;
        lookBookData[6] = lookBookSendToFriendConfirmationImageUrl;

        this.LoadLookBook(lookBookData); 
    }
    catch(exception){} 
};

/** 
* Set the position of the Dock Bar to the bottom of the Browser Window
* @alias setDockPosition
* @alias LookBook.setDockPosition
*/
LookBook.prototype.setDockPosition = function()
{
    try
    {
        $("#LookBookOverlay").css('top', (LookBook.prototype.getScrollY() + (document.documentElement.clientHeight - $("#LookBookOverlay")[0].offsetHeight)) + "px");
    }
    catch(exception){}
};

/** 
* Configures the state (height) of the DockBar (the LookBookOverlay and LookBookViewPort layers)
* @alias setDockPosition
* @alias LookBook.setDockPosition
* @param {String} The state the dock should be changed to. Can either be "mini", "midi" or "maxi"
*/
LookBook.prototype.setDockState = function(state)
{
  var endheight = "";
  var margintop = ""
  
  switch (state.toLowerCase())
  {
    case "mini":
        endheight = "25px";
        break;
    case "midi":
        endheight= "105px";
        break;
    case "maxi":
        endheight = document.documentElement.clientHeight;
        break;
    default : 
      endheight = "25px";
    }

    $("#LookBookOverlay").css('height', endheight);
    
    try
    {
      flashObject = document.LookBookFlash;
      flashObject.height= endheight;
    }
    catch(exception){}
};

/**
 * Control the UI so that the user can upgrade Flash
 * @method
 * @alias UpgradeFlash
 * @alias LookBook.UpgradeFlash
 */
LookBook.prototype.UpdateFlash = function()
{
  LookBook.prototype.setDockState('maxi');
  
  var so = new SWFObject(lookBookServerUrl + "LookBook/Flash/lookBook.swf", "LookBookFlash", "992", "600", "8", "#ffffff");
  so.addParam("wmode", "transparent");
  so.useExpressInstall(lookBookServerUrl + 'LookBook/Flash/expressinstall.swf');
  so.write("LookBookViewPort"); 
};

/*
 * Global Variables
 */
var previousClientHeight = "";
var previousClientWidth = "";
var lookBookServerUrl = ""; // base url for the site
var lookBookSharedData = 0; // Variable that contains a friends collection
var lookBookProductServiceUrl = ""; // Url for the GetProductById Service
var lookBookShareServiceUrl = ""; // Url for the ShareLookBook Service
var lookBookBasketServiceUrl = ""; // Url for the Auto Quick Basket Service
var lookBookSharedLandingPageUrl = ""; // Url for the Auto Quick Basket Service
var lookBookSendToFriendLandingImageUrl = ""; //Url for "Send to Friend" landing page image
var lookBookSendToFriendConfirmationImageUrl = ""; //Url for "Send to Friend" confirmation page image.