﻿var elementCount = 0;
var rowCount = 0;
var pageNumber = -10;
var pageSize = 16;

var test = "";

// ==============================================================================================================================
// VIEWER DETAIL TABS
// ==============================================================================================================================

// Build ------------------------------------------------------------------------------------------------------------------------------
function buildViewerDetailTabs(root, suppliedroot, widgetName) {

          //Tab and page containers
          $("<div>").attr("id", "detailTabs-tabsContainer").addClass("tabsContainer").appendTo("#detailTabs");
          //clear
          $("<div>").addClass("clear").appendTo("#detailTabs");
          $("<div>").attr("id", "detailTabs-pagesContainer").addClass("pagesContainer").appendTo("#detailTabs");

          //add tabs
          addViewerDetailTab(root, suppliedroot, widgetName, "options", "Purchase Options");
          addViewerDetailTab(root, suppliedroot, widgetName, "description", "Full Description");
          addViewerDetailTab(root, suppliedroot, widgetName, "general", "Selection Assistance");
          addViewerDetailTab(root, suppliedroot, widgetName, "review", "Recent Reviews (0)");
          addViewerDetailTab(root, suppliedroot, widgetName, "question", "Recent Questions (0)");

          //Select start tab
          selectViewerDetailTabs("options");

};

// Add Tabs------------------------------------------------------------------------------------------------------------------------------
function addViewerDetailTab(root, suppliedroot, widgetName, id, tabtext) {

          $("<div>").attr("id", "detailTabs-tab-" + id).html(tabtext).addClass("tab").click(function () { selectViewerDetailTabs(id); }).appendTo("#detailTabs-tabsContainer");
          $("<div>").attr("id", "detailTabs-page-" + id).addClass("page").appendTo("#detailTabs-pagesContainer");

};

// Select Tabs------------------------------------------------------------------------------------------------------------------------------
function selectViewerDetailTabs(tabId) {
          $("#[id^='detailTabs-tab-']").removeClass("tabselected");
          $("#detailTabs-tab-" + tabId).addClass("tabselected");
          $("#[id^='detailTabs-page-']").hide();
          $("#detailTabs-page-" + tabId).show()

};

//============================================================================================ TRY
// PRODUCT VIEWER LOAD
//============================================================================================ TRY

function widgetProductViewerLoad(suppliedroot, widgetName) {

          //root
          if (suppliedroot == "Nothing") { root = ""; } else { root = suppliedroot };


          //Layout Product Details and record the view
          buildViewerProductLayout(root, suppliedroot, widgetName);
          buildViewerProductFileLinks(root, suppliedroot, widgetName);
          buildViewerProductOptions(root, suppliedroot, widgetName);
          buildViewerProductLinks(root, suppliedroot, widgetName);
          buildViewerProductAttributes(root, suppliedroot, widgetName);
          buildViewerProductFeedback(root, suppliedroot, widgetName);

};

// ==============================================================================================================================
// VIEWER PRODUCT
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductLayout(root, suppliedroot, widgetName) {


          var productDef = ViewerProductDefinition[0].split("|");
          var timeStamp = (new Date).getTime();
          var elementname = productDef[0];
          var productDefinitionID = productDef[1];
          var brand = productDef[2];
          var descriptionshort = productDef[3];
          var descriptionlong = productDef[4];
          var additionalInfromation = productDef[5];
          var imagefileid = productDef[6];
          var imagepath = productDef[7].replace("~/", root);
          var imagethumbpath = productDef[8].replace("~/", root);
          var flashmessage = productDef[9];
          var retailprice = productDef[10];
          var retailpriceratio = productDef[11];
          var menuid = productDef[12];
          var reviewrating = productDef[13];
          var quantitysold = productDef[14];
          var viewcount = productDef[15];
          var giftwraptype = productDef[16];
          var producticons = productDef[17];
          var rewardpoints = productDef[18];
          var additionalinfoimagepath = productDef[19].replace("~/", root);

          //Record the product view+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
          processProductView(productDefinitionID);

          //site variables
          var siteCurrencySymbol = $("#siteCurrencySymbol").val();
          var siteExchangeRate = $("#siteExchangeRate").val();

          //formatt price
          //  var formattedPrice = CommaFormatted(CurrencyFormatted(lowprice * (siteExchangeRate / 100)));
          //  retailprice = siteCurrencySymbol + (formattedPrice);
          // retailprice = siteCurrencySymbol + retailprice;


          //Create heading
          var heading = descriptionshort;
          if (brand !== "") {
                    heading = brand + " - " + heading
          }

          //Left hand Image
          $("<div>").attr("id", elementname + "_col1").addClass("pve1").css({ "text-align": "center" }).appendTo("#" + widgetName + "_ViewerCol1");
          $("<div>").addClass("primaryimagecontainer").attr({ "id": "containerPrimaryImage" }).appendTo("#" + elementname + "_col1");
          changeViewerPrimaryImage(imagepath);
          //$("<img>").addClass("primaryimage").attr({ "id": "viewerPrimaryImage", "src": imagepath }).appendTo("#containerPrimaryImage");

          $("<div>").html("Hover to activate zoom<br/>(May take a few seconds)").addClass("imageclick").appendTo("#containerPrimaryImage");

          //Thumbs Area
          $("<img>").addClass("thumbsimage").attr({ "src": imagethumbpath }).click(function () { changeViewerPrimaryImage(imagepath); }).appendTo("#thumbspanelleft");

          //details contaner
          $("<div>").attr("id", elementname + "_col2").addClass("pve1").prependTo("#" + widgetName + "_ViewerCol2");

          //          //header bar
          //          $("<div>").attr("id", elementname + "_headerbar").addClass("headerbar").appendTo("#" + elementname + "_col2");
          //          $("<div>").attr("id", elementname + "_headerbarleft").addClass("headerbarleft").html("left").appendTo("#" + elementname + "_headerbar");
          //          $("<div>").attr("id", elementname + "_headerbarright").addClass("headerbarright").appendTo("#" + elementname + "_headerbar");



          //Title - heading
          $("<div>").html(heading + "<hr/>").addClass("title").appendTo("#" + elementname + "_col2");


          //Large Price & Reward Points
          $("<div>").attr("id", "pricePanel").addClass("pricepanel").appendTo("#" + elementname + "_col2");
          //$("<span>").html("Share this product").addClass("right").appendTo("#pricePanel");
          $("<div>").attr("id", "productShare").addClass("productshare right").appendTo("#pricePanel");
          $("<span>").attr("id", "price").html("Price").addClass("price").appendTo("#pricePanel");
          //Set the share details
          $("#productShare").share({
                    url: 'http://www.isssafety.com',
                    title: 'ISS Safety',
                    description: 'Lorem ipsum et dolor',
                    tags: 'share, tag, example',
                    services: ['all'],
                    img_size: 16,
                    a_target: '_blank'
          });
          if (rewardpoints !== "0" || giftwraptype !== "0") { $("<div>").attr({ "id": elementname + "_extrspanel" }).addClass("extraspanel").appendTo("#" + elementname + "_col2"); };
          if (rewardpoints !== "0") { $("<div>").html("Earn " + rewardpoints + " Extra Reward Points!").addClass("rewardpoints").appendTo("#" + elementname + "_extrspanel"); };
          if (giftwraptype !== "1") { $("<div>").html("Gift wrapping service available on this item.").addClass("giftwrap").appendTo("#" + elementname + "_extrspanel"); };

          //Description preview flash message
          $("<div>").attr("id", elementname + "_desriptionpreview").html(descriptionlong.substring(0, 250) + "....&nbsp&nbsp").addClass("description").appendTo("#" + elementname + "_col2");
          $("<span>").html("more >>").addClass("link").click(function () { selectViewerDetailTabs("description"); $("#Product").show(); $("#Product_openedIcon").show(); $("#Product_closedIcon").hide(); }).appendTo("#" + elementname + "_desriptionpreview");

          if (flashmessage !== "") { $("<div>").html(flashmessage).addClass("flashmessage").appendTo("#" + elementname + "_col2"); };

          if (producticons !== "") {
                    //Icons
                    $("<div>").attr("id", "iconpanel").addClass("iconpanel").appendTo("#" + elementname + "_col2");

                    var iconset = [];
                    iconset = producticons.split("--");
                    for (i = 1; i < iconset.length - 1; i++) {
                              for (y = 0; y < DataSetIcons.length; y++) {
                                        if (DataSetIcons[y].indexOf("-|" + iconset[i] + "|-") > -1) {
                                                  var iconDef = [];
                                                  iconDef = DataSetIcons[y].split("|-|");
                                                  insertIcon(root, suppliedroot, widgetName, iconDef[10].replace("~/", root), iconDef[8], iconDef[7])
                                        };

                              };

                    };

          };
          //buildInfoMenus();
          //$("<div>").html("<hr/>" + iconset[1] + "<hr/>").addClass("description").appendTo("#" + elementname + "_col2");

          //detailTabs
          $("<div>").attr("id", "detailTabs").addClass("pvdt1").appendTo("#Product");
          buildViewerDetailTabs(root, suppliedroot, widgetName);

          //Add description & additional information
          $("<div>").html(descriptionlong).addClass("description").appendTo("#detailTabs-page-description");
          if (additionalInfromation !== "") { $("<div>").html("<hr/>" + additionalInfromation).addClass("description").appendTo("#detailTabs-page-description"); };

          //Add additional info image
          $("<div>").attr({ "id": "detailTabs-subpage-general-text" }).addClass("description").appendTo("#detailTabs-page-general");
          $("<div>").attr({ "id": "detailTabs-subpage-general-image" }).addClass("description").appendTo("#detailTabs-page-general");
          $("<img>").attr({ "src": additionalinfoimagepath }).addClass("infoimage").appendTo("#detailTabs-subpage-general-image");

          //Simulate this thumb as clicked
          changeViewerPrimaryImage(imagepath);

};

// ==============================================================================================================================
// VIEWER PRODUCT OPTIONS
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductOptions(root, suppliedroot, widgetName) {

          //site variables
          var siteCurrencySymbol = $("#siteCurrencySymbol").val();
          var siteExchangeRate = $("#siteExchangeRate").val();

          $("<div>").attr("id", "optionsmenu").addClass("optionsmenu").appendTo("#detailTabs-page-options");
          $("<span>").html("Group options by").addClass("").appendTo("#optionsmenu");
          $("<span>").html(":").addClass("menuspacer").appendTo("#optionsmenu");
          $("<span>").html("Size").addClass("link").click(function () { }).appendTo("#optionsmenu");
          $("<span>").html("|").addClass("menuspacer").appendTo("#optionsmenu");
          $("<span>").html("Colour").addClass("link").appendTo("#optionsmenu");
          $("<span>").html("|").addClass("menuspacer").appendTo("#optionsmenu");
          $("<span>").html("Style").addClass("link").appendTo("#optionsmenu");

          $("<table>").attr("id", "optionstable").addClass("table_productviewer_options").appendTo("#detailTabs-page-options");
          $("<tr>").attr("id", "header_row").addClass("").appendTo("#optionstable");
          $("<th>").css({ "width": "390px", "text-align": "left", "padding": "4px" }).html("Code - Option").appendTo("#header_row");
          $("<th>").css({ "width": "70px", "text-align": "center", "padding": "4px" }).html("Style").appendTo("#header_row");
          $("<th>").css({ "width": "70px", "text-align": "center", "padding": "4px" }).html("Colour").appendTo("#header_row");
          $("<th>").css({ "width": "60px", "text-align": "center", "padding": "4px" }).html("Size").appendTo("#header_row");
          $("<th>").css({ "width": "60px", "text-align": "right", "padding": "4px" }).html("Price").appendTo("#header_row");
          $("<th>").css({ "width": "60px", "text-align": "right", "padding": "4px" }).html("Qty").appendTo("#header_row");
          $("<tbody>").attr("id", "optionstablebody").css({ "vertical-align": "top" }).appendTo("#optionstable");

          //site variables
          var siteCurrencySymbol = $("#siteCurrencySymbol").val();
          var siteExchangeRate = $("#siteExchangeRate").val();

          var lowprice = 100000, highprice = 0;

          for (var i = 0; i < ViewerProductOptionsDefinition.length; i++) {
                    var optionTemp = ViewerProductOptionsDefinition[i].split("|");
                    var retailprice = optionTemp[6];
                    if (lowprice > parseFloat(retailprice)) { lowprice = retailprice }
                    if (highprice < parseFloat(retailprice)) { highprice = retailprice }

                    insertViewerProductOptions(root, suppliedroot, widgetName, ViewerProductOptionsDefinition[i]);
          };

          //formatt price
          var formattedPrice = CommaFormatted(CurrencyFormatted(lowprice * (siteExchangeRate / 100)));
          if (lowprice !== highprice) {
                    retailprice = "from " + siteCurrencySymbol + (formattedPrice);
          } else {
                    retailprice = siteCurrencySymbol + (formattedPrice);
          };

          //retailprice = "£" + retailprice;
          $("#price").html(retailprice);

};

function insertViewerProductOptions(root, suppliedroot, widgetName, optionDefinition) {

          var optionDef = optionDefinition.split("|");
          var timeStamp = (new Date).getTime();
          var elementname = optionDef[0];
          var orderItem = optionDef[1];
          var descriptionextension = optionDef[2];
          var style = optionDef[3];
          var colour = optionDef[4];
          var size = optionDef[5];
          var retailprice = optionDef[6];
          var productid = optionDef[7];

          //site variables
          var siteCurrencySymbol = $("#siteCurrencySymbol").val();
          var siteExchangeRate = $("#siteExchangeRate").val();

          retailprice = siteCurrencySymbol + CommaFormatted(CurrencyFormatted(retailprice * (siteExchangeRate / 100)));

          //Add description extension
          if (descriptionextension !== "") { orderItem = orderItem + "  (" + descriptionextension + ")" };

          $("<tr>").attr("id", elementname + "_row").addClass("").appendTo("#optionstablebody");
          $("<td>").css({ "text-align": "left", "padding": "4px" }).html(orderItem).appendTo("#" + elementname + "_row");
          $("<td>").css({ "text-align": "center", "padding": "4px" }).html(style).appendTo("#" + elementname + "_row");
          $("<td>").css({ "text-align": "center", "padding": "4px" }).html(colour).appendTo("#" + elementname + "_row");
          $("<td>").css({ "text-align": "center", "padding": "4px" }).html(size).appendTo("#" + elementname + "_row");
          $("<td>").css({ "text-align": "right", "padding": "4px" }).html(retailprice).appendTo("#" + elementname + "_row");
          $("<td>").attr({ "id": elementname + "_order" }).css({ "text-align": "right", "padding": "4px" }).appendTo("#" + elementname + "_row");
          $("<span>").attr({ "id": elementname + "_orderbtn", "title": "Add to basket" }).addClass("ui-icon  ui-icon-cart ui-icon-outer right").appendTo("#" + elementname + "_order");
          $("<input>").attr({ "id": "Qty_" + elementname, "type": "text", "maxlength": "3", "value": "1", "title": "Quantity to order" }).addClass("orderqty right").appendTo("#" + elementname + "_order");
          //add to basket click
          $("#" + elementname + "_orderbtn").click(function () {
                    addToBasket(elementname, productid);
          });

          $("<tr>").attr("id", elementname + "_messagerow").addClass("").appendTo("#optionstablebody");
          $("<td>").attr({ "id": elementname + "_messagecell", "colspan": "6" }).css({ "text-align": "right", "padding": "4px" }).appendTo("#" + elementname + "_messagerow");
          $("<span>").attr("id", "Message_" + elementname).addClass("right").css({ "display": "none", "padding": "3px" }).appendTo("#" + elementname + "_messagecell");
};

// ==============================================================================================================================
// VIEWER PRODUCT FILE LINKS
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductFileLinks(root, suppliedroot, widgetName) {
          for (var i = 0; i < ViewerProductFileLinksDefinition.length; i++) {
                    insertViewerProductFileLinks(root, suppliedroot, widgetName, ViewerProductFileLinksDefinition[i]);
          };
};

function insertViewerProductFileLinks(root, suppliedroot, widgetName, fileLinkDefinition) {
          var fileLinkDef = fileLinkDefinition.split("|");
          var timeStamp = (new Date).getTime();
          var elementname = fileLinkDef[0];
          var linkType = fileLinkDef[1];
          var imagePath = fileLinkDef[2].replace("~/", root);
          var imageThumbPath = fileLinkDef[3].replace("~/", root);
          var imagefileid = fileLinkDef[4];

          $("<img>").addClass("thumbsimage").attr({ "id": elementname + "image", "src": imageThumbPath }).addClass("left ui-icon-outer").appendTo("#thumbspanelright");
          //  Add events--------------------------------------------------------------------------------------------------------------------------------
          $("#" + elementname + "image").click(function () {
                    changeViewerPrimaryImage(imagePath);
          });
};

// ==============================================================================================================================
// VIEWER PRODUCT ATTRIBUTES
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductAttributes(root, suppliedroot, widgetName) {
          var currentGroup = "";
          for (var i = 0; i < ViewerProductAttributeLinksDefinition.length; i++) {
                    var attributeLinkDef = ViewerProductAttributeLinksDefinition[i].split("|");
                    var timeStamp = (new Date).getTime();
                    var elementname = attributeLinkDef[0];
                    var group = attributeLinkDef[1];
                    var attribute = attributeLinkDef[2];
                    var value = attributeLinkDef[3];

                    //Add Headings
                    if (currentGroup !== group) {
                              $("<div>").addClass("attributeheader").html(group).appendTo("#detailTabs-subpage-general-text");
                              currentGroup = group;
                    };

                    // Add attributes
                    $("<span>").addClass("attribute").html(attribute + ":").appendTo("#detailTabs-subpage-general-text");
                    $("<span>").addClass("attributevalue").html(value).appendTo("#detailTabs-subpage-general-text");
                    $("<br>").appendTo("#detailTabs-subpage-general-text");
          };
};

// ==============================================================================================================================
// VIEWER LINKS
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductLinks(root, suppliedroot, widgetName) {
          for (var i = 0; i < ViewerProductLinksDefinition.length; i++) {
                    insertViewerProductLinks(root, suppliedroot, widgetName, ViewerProductLinksDefinition[i]);

          };
};

function insertViewerProductLinks(root, suppliedroot, widgetName, productLinkDefinition) {
          var productLinkDef = productLinkDefinition.split("|");
          var timeStamp = (new Date).getTime();
          var elementname = productLinkDef[0];
          var linkType = productLinkDef[1];
          var productDefinitionID = productLinkDef[2];
          var productDefinitionidFormatted = productLinkDef[3];
          var brand = productLinkDef[4];
          var descriptionshort = productLinkDef[5];
          var descriptionlong = productLinkDef[6];
          var imagepath = productLinkDef[7].replace("~/", root);
          var imagethumbpath = productLinkDef[8].replace("~/", root);
          var flashmessage = productLinkDef[9];
          var retailprice = productLinkDef[10];
          var listpriceratio = productLinkDef[11];

          $("<div>").attr("id", elementname + "_wrapper").addClass("ple1").appendTo("#" + linkType);
          $("<img>").addClass("image").attr({ "id": elementname + "image", "src": imagethumbpath }).appendTo("#" + elementname + "_wrapper");

          $("#" + elementname + "image").click(function () {

                    $("#ProductViewerPanel").load(root + "Content/Widgets/widgetProductViewer.aspx", { "root": suppliedroot, "recordID": productDefinitionID });

                    //  $("#ProductViewerPanel").load(root + "Content/Widgets/widgetProductViewer.aspx", { "root": suppliedroot, "recordID": productDefinitionID }, function () { $("#" + widgetName + "_pageLoading").hide(); pause(3000); $("#" + widgetName + "_page2").show(); });
          });

};


//============================================================================================ TRY
// PRODUCT SELECTOR LOAD
//============================================================================================ TRY

function widgetProductSelectorLoad(suppliedroot, widgetName) {

          //root
          var root = "";
          if (suppliedroot == "Nothing") { root = ""; } else { root = suppliedroot };


          // LOAD WIDGET DEFINITIONS & DELETE CONTAINER
          // -----------------------------------------------------------------------------------------------------------------------------------------------

          //define product defs array
          SelectorProductDefinitions = [];
          SelectorProductDefinitionsPriceSort = new Array();
          // SelectorProductDefinitionsPriceSort[0] = new Array();
          var i = 0;
          $("#ProductDefs span").each(function () {
                    SelectorProductDefinitions[i] = new Array();
                    SelectorProductDefinitions[i][0] = $(this).html();
                    //Add the array index cols for sorting
                    var temp = SelectorProductDefinitions[i][0];
                    var item = temp.split("|");

                    SelectorProductDefinitions[i][1] = item[8]; //Price
                    SelectorProductDefinitions[i][2] = item[11]; //Review
                    SelectorProductDefinitions[i][3] = item[13]; //View Count

                    i++;
          });
          $("#ProductDefs").remove();


          //Initalise settings
          pageNumber = 0
          pageSize = 16

          //Build
          var recordsetsize = SelectorProductDefinitions.length;
          // alert(SelectorProductDefinitions.length);
          switch (recordsetsize) {
                    case 0: //
                              try {
                                        showDisplayPage(99);
                                        $("#ProductSelectorEmptyArea").load("Content/Widgets/widgetInformationViewer.aspx", { "root": suppliedroot, "informationLink": "ProductSelectorEmpty" }, function () { $("#ProductSelectorEmptyArea").show(); showDisplayPage(1); });
                              } catch (e) { };
                              break;
                    case 1: // only one product so direct to viewer
                              try {

                                        $("#ProductSelectorNotEmptyArea").show();
                                        var temp = SelectorProductDefinitions[0][0];
                                        var item = temp.split("|");
                                        // alert(item[1])
                                        showProduct(root, suppliedroot, widgetName, item[1]); // temp 1 = product Def ID
                                        buildSelectorLayout(root, suppliedroot, widgetName);
                              } catch (e) { };
                              break;
                    default: // more than one then build the selector

                              $("#ProductSelectorNotEmptyArea").show();
                              buildSelectorLayout(root, suppliedroot, widgetName);
          };




};

// ==============================================================================================================================
// PRODUCT SELECTOR BUILD LAYOUT
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildSelectorLayout(root, suppliedroot, widgetName) {


          var layoutType = $("#" + widgetName + "_searchBar_filter_layoutView").val();
          var sortOrder = $("#" + widgetName + "_searchBar_filter_orderExpression").val();


          //Sort the product defs array
          switch (sortOrder) {
                    case "PriceAsc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return a[1] - b[1] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Price Ascending");
                              } catch (e) { };
                              break;
                    case "PriceDesc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return b[1] - a[1] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Price Descending");
                              } catch (e) { };
                              break;

                    case "ReviewAsc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return a[2] - b[2] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Review Ascending");
                              } catch (e) { };
                              break;
                    case "ReviewDesc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return b[2] - a[2] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Review Descending");
                              } catch (e) { };
                              break;

                    case "PopularityAsc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return a[3] - b[3] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Popularity Ascending");
                              } catch (e) { };
                              break;
                    case "PopularityDesc": //
                              try {
                                        SelectorProductDefinitions.sort(function (a, b) { return b[3] - a[3] });
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Popularity Descending");
                              } catch (e) { };
                              break;
                    case "NoSort": //
                              try {
                                        /* do Nothing */
                                        $("#" + widgetName + "_searchBar_filter_currentOrder").html("Not Applied");
                              } catch (e) { };
                              break;

                    default:
                              // Price Asc
                              SelectorProductDefinitions.sort(function (a, b) { return a[1] - b[1] });
          };

          // alert(layoutType + ' -- ' + sortOrder);
          elementCount = 99999;
          rowCount = 1;

          if (pageNumber < 0) { pageNumber = 0 };

          var startElement = pageNumber * pageSize;
          var endElement = startElement + pageSize;
          var maxElement = SelectorProductDefinitions.length;

          if (endElement > maxElement) { endElement = maxElement; pageNumber--; };

          //clear the pager  and products area
          $("#selectorPaging").empty();
          $("#" + widgetName + "_Products").empty();
          //Hide the selectors row
          $("#" + widgetName + "_searchBar_filter_selectorsrow").hide();

          if (endElement !== 0) {

                    //previous button
                    $("<div>").attr({ 'id': 'selectorPreviousPage', 'title': 'Previous' }).addClass("ui-icon ui-icon-triangle-1-w ui-icon-outer left").appendTo("#selectorPaging")
                    $("#selectorPreviousPage").die("click").live("click", function () { pageNumber--; buildSelectorLayout(root, suppliedroot, widgetName); });
                    $("<span>").addClass("spacerhorz3 left").html("|").appendTo("#selectorPaging")
                    //pager text
                    $("<div>").html("Showing " + (startElement + 1) + " to " + endElement + " of " + maxElement).addClass("left").appendTo("#selectorPaging");
                    //next button
                    $("<span>").addClass("spacerhorz3 left").html("|").appendTo("#selectorPaging")
                    $("<div>").attr({ 'id': 'selectorNextPage', 'title': 'Next' }).addClass("ui-icon ui-icon-triangle-1-e ui-icon-outer left").appendTo("#selectorPaging")
                    $("#selectorNextPage").die("click").live("click", function () { pageNumber++; buildSelectorLayout(root, suppliedroot, widgetName); });
                    //Show selectors row
                    $("#" + widgetName + "_searchBar_filter_selectorsrow").show();
                    //Clear short cut images
                    $("#widgetShortCutPanel").empty();
                    //Add Elements
                    // -----------------------------------------------------------------------------------------------------------------------------------------------
                    for (var i = startElement; i < endElement; i++) {
                              createSelectorElement(root, suppliedroot, widgetName, layoutType, SelectorProductDefinitions[i][0]);
                    };

          } else {
                    //pager text
                    $("<div>").html("No Products Returned ").addClass("left").appendTo("#selectorPaging");
                    $("#" + widgetName + "_Products").html("No Products Returned");

          };




          //$("#selectorPaging").html(startElement + " to " + endElement + " of " + SelectorProductDefinitions.length)



};

// ==============================================================================================================================
// PRODUCT SELECTOR CREATE ELEMENTS
// ==============================================================================================================================

function createSelectorElement(root, suppliedroot, widgetName, layoutType, SelectorProductDefinitions) {

          elementCount++;

          var productDef = SelectorProductDefinitions.split("|");
          var timeStamp = (new Date).getTime();
          var elementname = productDef[0];
          var productDefinitionID = productDef[1];
          var brand = productDef[2];
          var descriptionshort = productDef[3];
          var descriptionlong = productDef[4];
          var imagepath = productDef[5].replace("~/", root);
          var imagethumbpath = productDef[6].replace("~/", root);
          var flashmessage = productDef[7];
          var retailprice = productDef[8];
          var retailpriceratio = productDef[9];
          var menuid = productDef[10];
          var reviewrating = productDef[11];
          var quantitysold = productDef[12];
          var viewcount = productDef[13];
          var giftwraptype = productDef[14];

          //site variables
          var siteCurrencySymbol = $("#siteCurrencySymbol").val();
          var siteExchangeRate = $("#siteExchangeRate").val();

          //formatt price
          // retailprice = siteCurrencySymbol + (retailprice * (siteExchangeRate / 100));
          //retailprice = siteCurrencySymbol + retailprice;
          var formattedPrice = CommaFormatted(CurrencyFormatted(retailprice * (siteExchangeRate / 100)));
          retailprice = siteCurrencySymbol + (formattedPrice);
          // retailprice = siteCurrencySymbol + retailprice;

          //layout type
          // -----------------------------------------------------------------------------------------------------------------------------------------------
          $("#ime_1_siteShare").show();

          switch (layoutType) {
                    case "1": //Small images
                              try {

                                        //Build row and filler row
                                        if (elementCount > 7) {
                                                  rowCount++;
                                                  elementCount = 0;
                                                  $("<tr>").attr("id", "productRow_" + rowCount).addClass("productrow").appendTo("#" + widgetName + "_Products");
                                                  $("<td>").attr("id", "productCell_" + rowCount).appendTo("#productRow_" + rowCount);
                                                  nextSelectorFillerAd(rowCount, elementname, root, suppliedroot, widgetName);
                                        };

                                        $("<div>").attr("id", elementname + "_wrapper").addClass("pe1").appendTo("#productCell_" + rowCount);
                                        $("<img>").addClass("image ui-icon-outer").attr({ "id": elementname + "image", "src": imagethumbpath }).appendTo("#" + elementname + "_wrapper");

                                        if (brand !== "") { $("<div>").addClass("brand").attr({}).html(brand).appendTo("#" + elementname + "_wrapper") };
                                        if (descriptionshort !== "") { $("<div>").addClass("description").attr({}).html(descriptionshort).appendTo("#" + elementname + "_wrapper") };
                                        if (retailprice !== "") { $("<div>").addClass("price").attr({}).html(retailprice).appendTo("#" + elementname + "_wrapper") };
                                        if (flashmessage !== "") { $("<div>").addClass("flashmessage").attr({}).html(flashmessage).appendTo("#" + elementname + "_wrapper") };

                                        // $("<div>").addClass("ratingbarouter").attr({ "id": "ratingouter_" + elementname }).appendTo("#" + elementname + "_wrapper")
                                        //  $("<div>").addClass("ratingbarinner left").css({ 'width': '40%' }).attr({}).appendTo("#ratingouter_" + elementname)
                                        //$("#productrating_" + elementname).progressbar({ value: 37 });
                                        //   if (giftwraptype !== "0") { $("<div>").addClass("giftwrap").attr({}).html("Gift").appendTo("#" + elementname + "_wrapper") };

                              } catch (e) { };
                              break;
                    case "2": //large images
                              try {

                                        if (elementCount > 3) {
                                                  rowCount++;
                                                  elementCount = 0;
                                                  $("<tr>").attr("id", "productRow_" + rowCount).addClass("productrow").appendTo("#" + widgetName + "_Products");
                                                  $("<td>").attr("id", "productCell_" + rowCount).appendTo("#productRow_" + rowCount);
                                                  nextSelectorFillerAd(rowCount, elementname, root, suppliedroot, widgetName);
                                        };

                                        $("<div>").attr("id", elementname + "_wrapper").addClass("pe2").appendTo("#productCell_" + rowCount);
                                        $("<img>").addClass("image").attr({ "id": elementname + "image", "src": imagepath }).addClass("ui-icon-outer").appendTo("#" + elementname + "_wrapper");

                                        if (brand !== "") { $("<div>").addClass("brand").attr({}).html(brand).appendTo("#" + elementname + "_wrapper") };
                                        if (descriptionshort !== "") { $("<div>").addClass("description").attr({}).html(descriptionshort).appendTo("#" + elementname + "_wrapper") };
                                        if (retailprice !== "") { $("<div>").addClass("price").attr({}).html(retailprice).appendTo("#" + elementname + "_wrapper") };
                                        if (flashmessage !== "") { $("<div>").addClass("flashmessage").attr({}).html(flashmessage).appendTo("#" + elementname + "_wrapper") };
                                        //$("<div>").addClass("temp").attr({}).html(productDefinitionID).appendTo("#" + elementname + "_wrapper")

                              } catch (e) { };
                              break;

                    case "3": //Grid images
                              try {

                                        if (elementCount > 0) {
                                                  rowCount++;
                                                  elementCount = 0;
                                                  $("<tr>").attr("id", "productRow_" + rowCount).addClass("productrow").appendTo("#" + widgetName + "_Products");
                                                  $("<td>").attr("id", "productCell_" + rowCount).appendTo("#productRow_" + rowCount);
                                                  nextSelectorFillerAd(rowCount, elementname, root, suppliedroot, widgetName);
                                        };

                                        $("<div>").attr("id", elementname + "_wrapper").addClass("pe3").appendTo("#productCell_" + rowCount);
                                        $("<div>").attr("id", elementname + "_imagewrapper").addClass("imagewrapper left").appendTo("#" + elementname + "_wrapper");
                                        $("<img>").addClass("image").attr({ "id": elementname + "image", "src": imagethumbpath }).addClass("ui-icon-outer").appendTo("#" + elementname + "_imagewrapper");

                                        $("<div>").attr("id", elementname + "_detailwrapper").addClass("detailwrapper").appendTo("#" + elementname + "_wrapper");
                                        if (brand !== "") { $("<div>").addClass("brand").attr({}).html(brand).appendTo("#productCell_" + rowCount) };
                                        if (descriptionshort !== "") { $("<div>").addClass("description").attr({}).html(descriptionshort.toUpperCase()).appendTo("#" + elementname + "_detailwrapper") };
                                        if (descriptionlong !== "") { $("<div>").addClass("description").attr({}).html(descriptionlong).appendTo("#" + elementname + "_detailwrapper") };
                                        if (retailprice !== "") { $("<div>").addClass("price").attr({}).html(retailprice).appendTo("#" + elementname + "_detailwrapper") };
                                        if (flashmessage !== "") { $("<div>").addClass("flashmessage").attr({}).html(flashmessage).appendTo("#" + elementname + "_detailwrapper") };

                              } catch (e) { };
                              break;

          };

          // Add events
          // -----------------------------------------------------------------------------------------------------------------------------------------------

          $("#" + elementname + "image").live("click", function () {
                    //                    $("#" + widgetName + "_page1").hide();
                    //                    $("#" + widgetName + "_pageLoading").show();
                    //                    $("#" + widgetName + "_page2results").load(root + "Content/Widgets/widgetProductViewer.aspx", { "root": suppliedroot, "recordID": productDefinitionID, "menuID": menuid }, function () { $("#" + widgetName + "_pageLoading").hide(); testingPause(); $("#" + widgetName + "_page2").show(); });
                    showProduct(root, suppliedroot, widgetName, productDefinitionID);
          });

          // Short Cut Images
          $("<img>").addClass("image ui-icon-outer").attr({ "id": elementname + "imageshortcut", "src": imagethumbpath, "title": descriptionshort }).appendTo("#widgetShortCutPanel");
          $("#" + elementname + "imageshortcut").live("click", function () {
                    showProduct(root, suppliedroot, widgetName, productDefinitionID);
          });

};

//==============================================================================================================================
// NEXT SELECTOR FILLER AD
// ==============================================================================================================================

function nextSelectorFillerAd(rowCount, elementname, root, suppliedroot, widgetName) {

          var randomnumber = Math.floor(Math.random() * 11)

          var nextitemindex = Math.floor(Math.random() * DataSetSelectorFillerAds.length + 1);

          if (randomnumber > 4.9) {

                    var item = DataSetSelectorFillerAds[nextitemindex].split("|-|");

                    //var splitItem = item;
                    var productDefinitionID = item[5];
                    var adimagepath = item[7].replace("~/", "");
                    $("<tr>").attr("id", "productSpacerRow1_" + rowCount).addClass("spacerrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").appendTo("#productSpacerRow1_" + rowCount);

                    $("<tr>").attr("id", "productPromotionRow_" + rowCount).addClass("promotionrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").addClass("promotion").attr("id", "productPromotionCell_" + rowCount).appendTo("#productPromotionRow_" + rowCount);
                    $("<img>").attr({ "id": elementname + rowCount + "image", 'src': adimagepath, 'title': 'Select' }).addClass("").appendTo("#productPromotionCell_" + rowCount);

                    $("<tr>").attr("id", "productSpacerRow2_" + rowCount).addClass("spacerrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").appendTo("#productSpacerRow2_" + rowCount);

                    $("#" + elementname + rowCount + "image").live("click", function () {
                              //                    $("#" + widgetName + "_page1").hide();
                              //                    $("#" + widgetName + "_pageLoading").show();
                              //                    $("#" + widgetName + "_page2results").load(root + "Content/Widgets/widgetProductViewer.aspx", { "root": suppliedroot, "recordID": productDefinitionID, "menuID": menuid }, function () { $("#" + widgetName + "_pageLoading").hide(); testingPause(); $("#" + widgetName + "_page2").show(); });
                              showProduct(root, suppliedroot, widgetName, productDefinitionID);
                    });

                    //$("<div>").css("height", "50px").addClass("placeholder").html("New Advertisement Here").appendTo("#productPromotionCell_" + rowCount);
          } else {
                    $("<tr>").attr("id", "productSpacerRow1_" + rowCount).addClass("spacerrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").appendTo("#productSpacerRow1_" + rowCount);
                    $("<tr>").attr("id", "productDividerRow_" + rowCount).addClass("dividerrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").appendTo("#productDividerRow_" + rowCount);
                    $("<tr>").attr("id", "productSpacerRow2_" + rowCount).addClass("spacerrow").appendTo("#" + widgetName + "_Products");
                    $("<td>").appendTo("#productSpacerRow2_" + rowCount);


          };

};

// ==============================================================================================================================
// MISC
// ==============================================================================================================================

function insertIcon(root, suppliedroot, widgetName, src, title, informationlink) {
          if (informationlink !== "") {
                    $("<img>").attr({ "src": src, "title": title }).click(function () {
                              // alert("Load Info");
                              pageInformationLink(suppliedroot, informationlink);
                    })
          .addClass("icon ui-icon-outer").appendTo("#iconpanel");

          } else {
                    $("<img>").attr({ "src": src, "title": title }).addClass("icon ui-icon-border").appendTo("#iconpanel")
          };
};

function showProduct(root, suppliedRoot, widgetName, productDefinitionID) {
          $("#ime_1_siteShare").hide();
          $("#" + widgetName + "_page1").hide();
          $("#" + widgetName + "_pageLoading").show();
          $("#" + widgetName + "_page2results").load(root + "Content/Widgets/widgetProductViewer.aspx", { "root": suppliedRoot, "recordID": productDefinitionID }, function () { $("#" + widgetName + "_pageLoading").hide(); testingPause(); $("#" + widgetName + "_page2").show(); });
};

function changeViewerPrimaryImage(imagePath) {
          //Remove the current image
          $("#viewerPrimaryImage").remove();
          $("<img>").addClass("primaryimage").attr({ "id": "viewerPrimaryImage", "src": imagePath })
          .mouseout(function () { })
          .prependTo("#containerPrimaryImage");

          $('#viewerPrimaryImage').addimagezoom({
                    zoomrange: [3, 10],
                    magnifiersize: [300, 400],
                    magnifierpos: 'right',
                    cursorshade: true,
                    largeimage: imagePath.replace('Product/Images', 'OriginalFiles')
          })
};

function removeMagnifier() {
          $("[id^=magnifier]").remove();
          //$("#containerPrimaryImage").empty();
};

function hideMagnifier() {
          $("[id^=magnifier]").hide();
          //$("#containerPrimaryImage").empty();
};

function showMagnifier() {
          $("[id^=magnifier]").show();
          //$("#containerPrimaryImage").empty();
};

// PROCESS PRODUCT VIEW =====================================================================================================
function processProductView(ProductDefinitionID) {

          //Record the search
          ws_2g_Core.WSRecordProductView(ProductDefinitionID,
                                        NoAction1_SucceededCallback, TimeoutCallback, FailedCallback);

};



// PROCESS NO ACTION SUCCEEDED
function NoAction1_SucceededCallback(result) {
          if (result.Success == false) {
          } else {
          };
};


// ==============================================================================================================================
// VIEWER PRODUCT ATTRIBUTES
// ==============================================================================================================================

// -----------------------------------------------------------------------------------------------------------------------------------------------
function buildViewerProductFeedback(root, suppliedroot, widgetName) {

          // Build review page
          $("<div>").attr({ "id": "feedbackform-review" }).addClass("feedbackform").appendTo("#detailTabs-page-review");
          $("<div>").attr({ "id": "feedback-list-selector" }).addClass("feedbackselector link").html("View previous reviews")
          .click(function () { $("#feedbacklist-review").show(); $("#feedbackform-review").hide(); })
          .appendTo("#feedbackform-review");

          $("<div>").attr({ "id": "feedbacklist-review" }).addClass("feedbacklist").appendTo("#detailTabs-page-review");
          $("<div>").attr({ "id": "feedback-form-selector" }).addClass("feedbackselector link").html("Review this product")
          .click(function () { $("#feedbacklist-review").hide(); $("#feedbackform-review").show(); })
          .appendTo("#feedbacklist-review");

          // Build question page
          $("<div>").attr({ "id": "feedbackform-question" }).addClass("feedbackform").appendTo("#detailTabs-page-question");
          $("<div>").attr({ "id": "feedback-list-selector" }).addClass("feedbackselector link").html("View previous questions and answers")
          .click(function () { $("#feedbacklist-question").show(); $("#feedbackform-question").hide(); })
          .appendTo("#feedbackform-question");
          $("#tablefeedbackform-question").appendTo("#feedbackform-question");

          $("<div>").attr({ "id": "feedbacklist-question" }).addClass("feedbacklist").appendTo("#detailTabs-page-question");
          $("<div>").attr({ "id": "feedback-form-selector" }).addClass("feedbackselector link").html("Ask a question about this product")
          .click(function () { $("#feedbacklist-question").hide(); $("#feedbackform-question").show(); })
          .appendTo("#feedbacklist-question");
          $("#tablefeedbackform-review").appendTo("#feedbackform-review");

          var questioncount = 0, reviewcount = 0;

          for (var i = 0; i < ViewerProductFeedbackDefinition.length; i++) {

                    var feedbackDef = ViewerProductFeedbackDefinition[i].split("|");
                    var timeStamp = (new Date).getTime();
                    var elementname = feedbackDef[0];
                    var feedbacktypeid = feedbackDef[1];
                    var editedname = feedbackDef[2];
                    var editedfeedback = feedbackDef[3];
                    var rating = feedbackDef[4];
                    var answer = feedbackDef[5];

                    switch (feedbacktypeid) {
                              case "3": //Question
                                        try {
                                                  $("<hr>").appendTo("#feedbacklist-question");
                                                  $("<div>").addClass("feedbackheader").html(editedfeedback).appendTo("#feedbacklist-question");
                                                  $("<div>").addClass("feedbacktext").html(answer).appendTo("#feedbacklist-question");
                                                  questioncount++;
                                        } catch (e) { };
                                        break;
                              case "4": //review
                                        try {
                                                  $("<hr>").appendTo("#feedbacklist-review");
                                                  $("<div>").addClass("feedbackheader").html(rating).appendTo("#feedbacklist-review");
                                                  $("<div>").addClass("feedbacktext").html(editedfeedback).appendTo("#feedbacklist-review");
                                                  reviewcount++;
                                        } catch (e) { };
                                        break;

                    };

          };

          if (questioncount < 1) {
                    $("<div>").addClass("feedbacknodata").html("No questions relating to this product have been asked ").appendTo("#feedbacklist-question");
          } else {
                    $("#detailTabs-tab-question").html('Recent Questions (' + questioncount + ')');
          };
          if (reviewcount < 1) {
                    $("<div>").addClass("feedbacknodata").html("No reviews relating to this product have been placed").appendTo("#feedbacklist-review");
          } else {
                    $("#detailTabs-tab-review").html('Recent Reviews (' + reviewcount + ')');
          };

};

                      
