﻿function pause(milliseconds) {
          var dt = new Date();
          while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
};

function testingPause() {
          var dt = new Date();
          while ((new Date()) - dt <= 0) { /* Do nothing */ }
};

//// ==============================================================================================================================
//// PROCESS PICK
//// ==============================================================================================================================

//// PROCESS PICK =========================================================================================
//function processPick(GUID) {
//         // if (validateProcessPick(GUID)) {
//                    var salesorderlineid = "", notes = "", despatchqty = "", giftwrapqty ="";
//                    try { salesorderlineid = $("#SalesOrderLineID_" + GUID).val(); } catch (e) { };
//                    try { notes = $("#Notes_" + GUID).val(); } catch (e) { };
//                    try { despatchqty = $("#DespatchQty_" + GUID).val(); } catch (e) { };
//                    try { giftwrapqty = $("#GiftWrapQty_" + GUID).val(); } catch (e) { };
//                    ws_2g_Core.WSProcessPick(GUID, salesorderlineid, notes, despatchqty, giftwrapqty,
//                                userLogOn_SucceededCallback, TimeoutCallback, FailedCallback);
//         // };
//};

//// PROCESS PICK SUCCEEDED
//function processPick_SucceededCallback(result) {
//          var GUID = result.GUID
//          //clear any message after delay
//          if (result.Success == false) {
//                    jAlert(result.ErrorMessage);
//          } else {
//                    jAlert("pick completed");
//          };
//};

//// VALIDATE PROCESS PICK
//function validateProcessPick(GUID) {
//          //Set initial conditions
//          var errormessage = "", returnvalue = true;

//          //Form Fields
//          var username = $("#UserName_" + GUID);
//          var password = $("#Password_" + GUID);

//          var allFields = $([]).add(username, password);

//          //Validate Form Fields
//          if (checkLength(username, 1, 10000)) {
//                    username.removeClass("errorhighlight");
//          } else {
//                    username.addClass("errorhighlight");
//                    errormessage += "Please enter your name.";
//                    returnvalue = false;
//          };


//          //Display or clear errors
//          if (returnvalue == false) {
//                    jAlert(errormessage, appname);
//          } else {
//                    allFields.removeClass("errorhighlight");
//          };

//          return returnvalue;
//};

//// ==============================================================================================================================
//// END USER LOG ON
//// ==============================================================================================================================


function CurrencyFormatted(amount) {
          var i = parseFloat(amount);
          if (isNaN(i)) { i = 0.00; }
          var minus = '';
          if (i < 0) { minus = '-'; }
          i = Math.abs(i);
          i = parseInt((i + .005) * 100);
          i = i / 100;
          s = new String(i);
          if (s.indexOf('.') < 0) { s += '.00'; }
          if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
          s = minus + s;
          return s;
};

function CommaFormatted(amount) {
          var delimiter = ","; // replace comma if desired
          var a = amount.split('.', 2)
          var d = a[1];
          var i = parseInt(a[0]);
          if (isNaN(i)) { return ''; }
          var minus = '';
          if (i < 0) { minus = '-'; }
          i = Math.abs(i);
          var n = new String(i);
          var a = [];
          while (n.length > 3) {
                    var nn = n.substr(n.length - 3);
                    a.unshift(nn);
                    n = n.substr(0, n.length - 3);
          }
          if (n.length > 0) { a.unshift(n); }
          n = a.join(delimiter);
          if (d.length < 1) { amount = n; }
          else { amount = n + '.' + d; }
          amount = minus + amount;
          return amount;
};

// ==============================================================================================================================
// GLOBAL VARIABLES
// ==============================================================================================================================
var progressCounter = 0;
var helptext = "Need help or have a question";
var appname = "ISS Safety";
// ==============================================================================================================================
// INITALISATION AND TIMED REPEAT 
// ==============================================================================================================================

//Clock
var d = new Date();
var t = d.toLocaleTimeString();
$('#messageDTG').html(t);

//Type helptext
type(helptext, 75, 1, "HelpText");

//Each 50 ms
var int100 = window.setInterval(refresh100, 50);
function refresh100() {
          //    //Progress bar
          //    progressCounter++
          //    if (progressCounter > 100) { progressCounter = 0 }
          //    $("#progressBar").progressbar({ value: progressCounter });
};

//Each Second
var int1000 = window.setInterval(refresh1000, 1000);
function refresh1000() {
          //Clock
          var d = new Date();
          var t = d.toLocaleTimeString();
          $('#messageDTG').html(t);

};

//Each Minute
var int60000 = window.setInterval(refresh60000, 60000);
function refresh60000() {
          //Type helptext
          type(helptext, 75, 1, "HelpText");

};

//Each Ten Minutes
var int600000 = window.setInterval(refresh600000, 600000);
function refresh600000() {

};

// ==============================================================================================================================
// SHOW PROGRESS
// ==============================================================================================================================

function showProgress(target) {
          $("#" + target).empty();
          progressCounter = 1;
          $("<div>").attr({ "id": "progressBar" }).appendTo("#" + target);

};


// ==============================================================================================================================
// GET EXTERNAL LINKS
// ==============================================================================================================================

function getExtermalLink(source) {

          //set default qty
          var displayqty = 15;

          switch (source) {
                    case "bbcsport":
                              try {
                                        $.getJSON("http://pipes.yahoo.com/georgemccombe/" + source + "?_render=JSON&_callback=?", function (data) {
                                                  $.each(data.value.items, function (i, item) {
                                                            try { storeExternalLink(source, "", item.title, item.description, item.link, item['media:thumbnail'].url); } catch (e) { };
                                                            return (i > displayqty) ? false : null;
                                                  });
                                        });
                              } catch (e) { };
                              break;

                    case "bbcworldnews":
                              try {
                                        $.getJSON("http://pipes.yahoo.com/georgemccombe/" + source + "?_render=JSON&_callback=?", function (data) {
                                                  $.each(data.value.items, function (i, item) {
                                                            try { storeExternalLink(source, "", item.title, item.description, item.link, item['media:thumbnail'][0].url); } catch (e) { };
                                                            return (i > displayqty) ? false : null;
                                                  });
                                        });
                              } catch (e) { };
                              break;
                    case "bbcbusiness":
                              try {
                                        $.getJSON("http://pipes.yahoo.com/georgemccombe/" + source + "?_render=JSON&_callback=?", function (data) {
                                                  $.each(data.value.items, function (i, item) {
                                                            try { storeExternalLink(source, "", item.title, item.description, item.link, item['media:thumbnail'][0].url); } catch (e) { };
                                                            return (i > displayqty) ? false : null;
                                                  });
                                        });
                              } catch (e) { };
                              break;


          };

};
// ==============================================================================================================================
// STORE EXTERNAL LINKS
// ==============================================================================================================================

// STORE LINK 
function storeExternalLink(Source, SourceGUID, Title, Description, Link, ThumbLink) {
          ws_2g_Core.WSStoreExternalLink(Source, SourceGUID, Title, Description, Link, ThumbLink,
                    storeExternalLink_SucceededCallback, TimeoutCallback, FailedCallback);
};

// STORE LINK  SUCCEEDED
function storeExternalLink_SucceededCallback(result) {
          if (result.Success == false) {
                    //ignore

          } else {

                    //ignore

          };
};


// ==============================================================================================================================
// CREATE WIDGET ICON
// ==============================================================================================================================
// -----------------------------------------------------------------------------------------------------------------------------------------------
function createWidgetIcon(widgetDefinition) {


          var widgetDef = widgetDefinition.split("|");
          var timeStamp = (new Date).getTime();
          var type = widgetDef[0];
          var widgetname = getUniqueID();
          var name = widgetDef[1];
          var title = widgetDef[2];
          var description = widgetDef[3];
          var URL = widgetDef[4].replace("TIMESTAMP", timeStamp);
          var shortCutButton = widgetDef[5];
          var autoOpen = widgetDef[6];
          var widgetIcon = widgetDef[7].replace("~/", "");
          var width = widgetDef[8];
          var height = widgetDef[9];
          var displaypage = widgetDef[10];
          var displayarea = widgetDef[11];

          $("<span>").attr("id", widgetname + "_iconwrapper").addClass("icon_wrapper").appendTo("#" + displayarea);
          $("<img/>").attr({ "id": widgetname + "_icon", "src": widgetIcon, "title": widgetIcon }).addClass("icon_image").appendTo("#" + widgetname + "_iconwrapper");
          $("<div>").addClass("icon_title").html(title).appendTo("#" + widgetname + "_iconwrapper");

          $("#" + widgetname + "_icon").live('click', function () {
                    createWidget(widgetDefinition, "cmWorkArea");
          });


};
// ==============================================================================================================================
// CREATE WIDGET
// ==============================================================================================================================
// -----------------------------------------------------------------------------------------------------------------------------------------------
function createWidget(widgetDefinition, overrideDisplayArea) {

          var widgetDef = widgetDefinition.split("|");
          var timeStamp = (new Date).getTime();
          var type = widgetDef[0];
          var widgetname = getUniqueID();
          var name = widgetDef[1];
          var title = widgetDef[2];
          var description = widgetDef[3];
          var URL = widgetDef[4].replace("TIMESTAMP", timeStamp);
          var shortCutButton = widgetDef[5];
          var autoOpen = widgetDef[6];
          var widgetIcon = widgetDef[7];
          var width = widgetDef[8];
          var height = widgetDef[9];
          var displaypage = widgetDef[10];
          var displayarea = widgetDef[11];
          // displayarea == overrideDisplayArea;
          if (overrideDisplayArea !== "") { displayarea = overrideDisplayArea; };


          $("<div>").attr("id", widgetname + "_wrapper").addClass("widget_wrapper").appendTo("#" + displayarea);
          $("<div>").addClass("widget_box").attr("id", widgetname).appendTo("#" + widgetname + "_wrapper");
          $("<div>").addClass("widget_title").attr("id", widgetname + "Title").appendTo("#" + widgetname);

          //Title contents
          $("<div>").addClass("widget_titlebuttonL ui-icon ui-icon-triangle-2-n-s").attr("id", widgetname + "Expand").attr("title", "Expand or collapse content").appendTo("#" + widgetname + "Title");
          $("<div>").addClass("widget_titlebuttonL ui-icon ui-icon-refresh").attr({ "id": widgetname + "Refresh", "title": "Refresh and reload contents" }).css("display", "none").appendTo("#" + widgetname + "Title");
          $("<div>").addClass("widget_titletext").attr("id", widgetname + "TitleText").text(title).appendTo("#" + widgetname + "Title");

          $("#" + widgetname + "Expand").live('click', function () {
                    $("#" + widgetname + "Content").slideToggle();
                    if ($("#" + widgetname + "Content").html() == "") {
                              //If empty load content form server and show refresh button
                              $("#" + widgetname + "Refresh").trigger("click");
                              $("#" + widgetname + "Refresh").show();
                    } else if (/\d\|{2}$/.test($("#" + widgetname + "Content").html()) == true) {
                              //if stored '/\d\|{2}$/' then get content from store and show refresh button
                              $("#" + widgetname + "Content").html(GetIt(widgetname + "Content"));
                              $("#" + widgetname + "Refresh").show();
                    } else {
                              //Put content in store and remove from DOM and hide refresh button
                              $("#" + widgetname + "Refresh").hide();
                              PutIt(widgetname + "Content");

                    };
          });

          switch (type) {
                    case "1":
                              //Refresh/reset button
                              $("#" + widgetname + "Refresh").live('click', function () {
                                        $("#" + widgetname + "Content").empty();
                                        $("#" + widgetname + "Content").slideDown();
                                        $("#" + widgetname + "Content").load(URL);
                              });
                              break;

                    case "2":
                              $("#" + widgetname + "Refresh").live('click', function () {
                                        $("#" + widgetname + "Content").empty();
                                        $("<iframe>").attr({ "id": widgetname + "Frame", "src": URL, "width": width, "height": height, "frameborder": "0" }).css({ "z-Index": "1000" }).appendTo("#" + widgetname + "Content");
                                        $("#" + widgetname + "Content").slideDown("fast");
                              });
                              break;

          };


          // Add content area
          $("<div>").addClass("widget_content").attr({ "id": widgetname + "Content" }).hide().appendTo("#" + widgetname);

          // Show content
          if (autoOpen == "Y") {
                    $("#" + widgetname + "Expand").trigger("click");
          };


};
// ==============================================================================================================================
// KEY CODE
// ==============================================================================================================================

// PROCESS KEY CODE
function processKeyCode() {
          if (validateProcessKeyCode()) {
                    var KeyCode = "";
                    try { KeyCode = $("#txtKeyCode").val(); } catch (e) { };
                    switch (KeyCode) {
                              case "newnotice":
                                        $('#layoutpages').hide();
                                        $('<iframe>').css({ 'height': '600px' }).attr({ 'src': '2g/Content/Forms/formNoticeBoards.aspx' }).appendTo('#keycodepage_results');
                                        //$('#keycodepage_results').html(KeyCode);
                                        $('#keycodepage').show();
                                        break;
                              case "newrequest":
                                        $('#layoutpages').hide();
                                        $('<iframe>').css({ 'height': '600px' }).attr({ 'src': '2g/Content/Forms/formCustomerRequests.aspx' }).appendTo('#keycodepage_results');
                                        //$('#keycodepage_results').html(KeyCode);
                                        $('#keycodepage').show();
                                        break;
                              default:
                                        ws_2g_Core.WSProcessKeyCode(KeyCode,
                                        processKeyCode_SucceededCallback, TimeoutCallback, FailedCallback);
                                        $('#layoutpages').hide(); $('#keycodepage').show();

                    };


                    //  ReturnString.Append("$(""#" & ModuleName & "_page2iframe"").css({""height"":""600px""}).attr({""src"": """ & Root & "2g/Content/Forms/formNoticeBoards.aspx?mode=" & getUniqueID() & "&recordID=" & Paramater2 & """});")



          };
};

// PROCESS KEY CODE SUCCEEDED
function processKeyCode_SucceededCallback(result) {
          if (result.Success == false) {
                    //show the error message
                    $("#keycodepage_results").html(result.ErrorMessage)
          } else {
                    //show success message and clear the original message
                    $("#keycodepage_results").html(result.HTMLString)
          };
};

// VALIDATE PROCESS KEY CODE
function validateProcessKeyCode() {
          //Set initial conditions
          var returnvalue = true;

          //Form Fields
          var KeyCode = $("#txtKeyCode");

          //Validate Form Fields
          if (checkLength(KeyCode, 1, 10000)) {
          } else {
                    returnvalue = false;
          };

          return returnvalue;

};
// ==============================================================================================================================
// REFRESH FUNCTIONS
// ==============================================================================================================================

// GET MESSAGE LATEST 
function getMessageLatest(Root) {
          ws_2g_Core.WSGetMessageLatest(Root,
                    getMessageLatest_SucceededCallback, TimeoutCallback, FailedCallback);
};

// GET MESSAGE LATEST SUCCEEDED
function getMessageLatest_SucceededCallback(result) {
          if (result.Success == false) {
                    //show the error message
                    $("#messageLatest").html(result.ErrorMessage);
          } else {
                    setTimeout(function () {
                              $("#messageLatestLink").removeClass('highlight', 1500);
                    }, 1500);
                    //show success message and clear the original message
                    $("#messageLatest").html(result.HTMLString);
                    type(result.HTMLString2, 75, 1, "messageLatestLink");
          };
};

// TYPE OUTPUT   
function type(text, delay, currentChar, destination) {

          $("#" + destination).html(text.substring(0, currentChar));
          currentChar++
          if (currentChar > text.length) {
                    //currentChar=1;
                    //setTimeout(function() {type(text,delay,currentChar,destination);}, 1000);
          }
          else {
                    setTimeout(function () { type(text, delay, currentChar, destination); }, delay);
          }
};





// GET LISTING PRICE CHECK=========================================================================================
function GetListingPriceCheck(GUID) {
          if (ValidateAddToBasket(GUID)) {
                    $("#ListingMessage_" + GUID).html("Checking price and availability ... ");
                    var PartNumber = "", Quantity = "0";
                    try { PartNumber = $("#PartNumber_" + GUID).html(); } catch (e) { };
                    try { Quantity = $("#ListingQuantity_" + GUID).val(); } catch (e) { };
                    //Starttime.getDate();
                    ws_2g_Core.WSGetListingPriceCheck(GUID, PartNumber, Quantity,
                        GetListingPriceCheck_SucceededCallback, TimeoutCallback, FailedCallback);
          };
};

// GET LISTING PRICE CHECK RESULT
function GetListingPriceCheck_SucceededCallback(result) {
          var GUID = result.GUID
          //clear any message after delay
          setTimeout(function () {
                    $("#ListingMessage_" + GUID).html("");
          }, 2500);
          if (result.Success == false) {
                    //show the error message
                    $("#ListingMessage_" + GUID).html(result.ErrorMessage);
          } else {
                    //show success message and clear the original message
                    $("#ListingMessage_" + GUID).html("Price check complete ...");
                    $("#ListingUnitPrice_" + GUID).html(result.HTMLString);
                    $("#ListingStock_" + GUID).html(result.HTMLString2);
          };
};


// ==============================================================================================================================
// VALIDATION FUNCTIONS
// ==============================================================================================================================

function showErrors(errorarea, errormessage) {
          setTimeout(function () {
                    errorarea.html("").hide();
          }, 2500);
          errorarea.attr({ innerHTML: errormessage }).show();
};


function showMessage(messagearea, message) {
          messagearea.attr({ innerHTML: message }).addClass('ui-state-highlight');
          setTimeout(function () {
                    messagearea.removeClass('ui-state-highlight', 1500);
          }, 500);
};

function checkLength(o, min, max) {
          if ($.trim(o.val()).length > max || $.trim(o.val()).length < min) {
                    return false;
          } else {
                    return true;
          };

};

function checkTextArea(o) {
          var content = $.trim(o.html());
          if (content =="") {
                    return false;
          } else {
                    return true;
          };

};

function checkRegexp(o, regexp) {
          //          if (regexp == /emailaddress/) { regexp = /\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/ };
          //          if (regexp == /integer/) { regexp = /^[1-9]\d*$/ };
          //          if (regexp == /zerointeger/) { regexp = /^[0-9]\d*$/ };

          if (!(regexp.test(o.val()))) {
                    return false;
          } else {
                    return true;
          }

}
// ==============================================================================================================================
// SELECTOR
// ==============================================================================================================================

// SHOW SELECTOR -------------------------------------------------------------------------------------------
function ShowSelector(SelectionList, TargetControl1, TargetControl2, TargetControl3, TargetControl4, Parameter1, Parameter2) {
          ws_2g_Core.WSShowSelector(SelectionList, TargetControl1, TargetControl2, TargetControl3, TargetControl4, Parameter1, Parameter2,
                    ShowSelector_SucceededCallback, TimeoutCallback, FailedCallback);
};

function ShowSelector_SucceededCallback(result) {
          SelectorDialog1.innerHTML = result.HTMLString;
          var DialogOpts = {
                    title: "Select",
                    resizable: false,
                    zIndex: 5000,
                    modal: true,
                    width: 554,
                    height: 400,
                    position: [50, 50]
          };

          $("#SelectorDialog1").dialog(DialogOpts);

};

// CLOSE SELECTOR  -------------------------------------------------------------------------------------------
function CloseSelector() {
          $("#SelectorDialog1").dialog("close");
};

// GET SELECTOR CONTENT  -------------------------------------------------------------------------------------------
function GetSelectorContent(SelectionList, TargetControl1, TargetControl2, TargetControl3, TargetControl4, Parameter1, Parameter2) {
          // Get filter panel values if applicable - FilterCell is FilterCell 

          var RowCount = "", SearchText = "", OrderByExpression = "", SortByExpression = "";
          try { RowCount = $get("Selector_searchBar_filter_rowCount").value; } catch (e) { };
          try { SearchText = $get("Selector_searchBar_filter_searchText").value; } catch (e) { };
          try { OrderByExpression = $get("Selector_searchBar_filter_orderExpression").value; } catch (e) { };
          try { SortByExpression = $get("Selector_searchBar_filter_sortExpression").value; } catch (e) { };

          ws_2g_Core.WSGetSelectorContent(SelectionList, TargetControl1, TargetControl2, TargetControl3, TargetControl4, Parameter1, Parameter2,
                    RowCount, SearchText, OrderByExpression, SortByExpression,
                    GetSelectorContent_SucceededCallback, TimeoutCallback, FailedCallback);
};

function GetSelectorContent_SucceededCallback(result) {
          try {
                    var TargetControl = $get(result.HTMLTarget);
                    TargetControl.innerHTML = result.HTMLString;
          } catch (e) { };
};

// SET SELECTOR OUTPUT  -------------------------------------------------------------------------------------------
function SetSelectorOutput(ControlID, Content, ContentType, ApplyAction) {
          try {
                    var TargetControl = $get(ControlID);
                    switch (ContentType) {
                              case "html":
                                        if (ApplyAction == "Append") {
                                                  TargetControl.innerHTML = TargetControl.innerHTML + Content;
                                        } else {
                                                  TargetControl.innerHTML = Content;
                                        };
                                        break;
                              default:
                                        if (ApplyAction == "Append") {
                                                  TargetControl.value = TargetControl.value + " - " + Content;
                                        } else {
                                                  TargetControl.value = Content;
                                        };

                    };
          } catch (e) { };

          //    CloseSelector();
};


// ==============================================================================================================================
// PAGE TABS
// ==============================================================================================================================

// SET PAGE TABS SELECT EVENT  -------------------------------------------------------------------------------------------
function pagesTabsSelect(event, tab) {
          //set the selected page
          selectedPage = tab.index;
          for (var x = 0; x < $("#pagesTabs").tabs("length") - 1; x++) {
                    //FOR EACH TAB PAGE (Less the last tab(Basket)) - Store all content that has been loaded and not already stored
                    if ($("#pagesTabs-" + x).html() !== "" && /\d\|{2}$/.test($("#pagesTabs-" + x).html()) !== true) {
                              PutIt("pagesTabs-" + x);
                    };
          };
          //get the selected tab content
          if (/\d\|{2}$/.test($("#pagesTabs-" + selectedPage).html()) == true) {
                    GetIt("pagesTabs-" + selectedPage);
          };
};



// ==============================================================================================================================
// DIALOG
// ==============================================================================================================================

// SHOW DIALOG  -------------------------------------------------------------------------------------------
function ShowDialog(Configuration, Param1, Param2, Param3) {
          $("#Dialog1").empty();
          switch (Configuration) {
                    case "Message":
                              $("#Dialog1").html(Param2.split('_').join(' '));
                              var DialogOpts = {
                                        title: Param1,
                                        dragable: false,
                                        modal: true,
                                        close: function () {
                                                  // $("#" + Param1).appendTo("#" + Param1 + "Wrapper");
                                                  CloseDialog();
                                        },
                                        buttons: {
                                                  Ok: function () {
                                                            $(this).dialog("close");
                                                  }
                                        }
                              };
                              break;

                    case "Form":
                              $("#Dialog1").load(Param2);
                              var DialogOpts = {
                                        title: Param1,
                                        modal: true,
                                        close: function () {
                                                  $("#" + Param1).appendTo("#" + Param1 + "Wrapper");
                                                  CloseDialog();
                                        }

                              };
                              break;
          };

          //open the dialog


          $("#Dialog1").dialog(DialogOpts);

          //Post open operations
          switch (Configuration) {
                    case "xxx":
                              $(".ui-dialog-titlebar").hide();
                              $(".ui-dialog-titlebar").removeClass('ui-adjust-widget-header-1');
                              break;
                    default:
                              $(".ui-dialog-titlebar").show();
                              $(".ui-dialog-content").css("overflow", "hidden");
                              $(".ui-dialog-content").css("padding", "0px");
                              $(".ui-dialog-titlebar").addClass('ui-adjust-widget-header-1');
          };

};

// CLOSE DIALOG  -------------------------------------------------------------------------------------------
function CloseDialog() {

          $("#Dialog1").dialog("destroy");
};

// ==============================================================================================================================
// INTERUPT
// ==============================================================================================================================

// SHOW INTERUPT  -------------------------------------------------------------------------------------------
function ShowInterupt(Type, Param1, Param2, Param3) {
          switch (Type) {
                    case "LogOn":
                              $('#layoutpages').hide();
                              $('#InteruptLogOnContainer').show();
                              break;

          };

};

// CLOSE INTERUPT  -------------------------------------------------------------------------------------------
function CloseInterupt(Type) {
          switch (Type) {
                    case "LogOn":
                              $('#InteruptLogOnContainer').hide();
                              $('#layoutpages').show();
                              break;

          };
};

// ==============================================================================================================================
// AJAX SETUP
// ==============================================================================================================================

// AJAX SETUP  -------------------------------------------------------------------------------------------
function AjaxSetup() {
          //Ajax handlers
          $('#defaultpageContent').ajaxError(function (info, xhr) {
                    $(info.target)
                            .html('<div>Failed at ' + new Date() + '</div>')
                            .append('<div>Status: ' + xhr.status + ' ' + xhr.statusText + '</div>');
          });

};


// ==============================================================================================================================
// WEB SERVICES FAIL & TIMEOUT
// ==============================================================================================================================

// CALL FAILED  -------------------------------------------------------------------------------------------
function FailedCallback(error) {
          //alert(arg.get_message);
          alert("Stack Trace: " + error.get_stackTrace() + "/r/n" +
          "Error: " + error.get_message() + "/r/n" +
          "Status Code: " + error.get_statusCode() + "/r/n" +
          "Exception Type: " + error.get_exceptionType() + "/r/n" +
          "Timed Out: " + error.get_timedOut());

};

// CALL TIMEOUT  -------------------------------------------------------------------------------------------
function TimeoutCallback(error) {
          alert("Stack Trace: " + error.get_stackTrace() + "/r/n" +
          "Error: " + error.get_message() + "/r/n" +
          "Status Code: " + error.get_statusCode() + "/r/n" +
          "Exception Type: " + error.get_exceptionType() + "/r/n" +
          "Timed Out: " + error.get_timedOut());
};

// ==============================================================================================================================
// ERROR HANDLERS
// ==============================================================================================================================
function windowErrorHandler(msg, url, linenumber) {
          alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
          return true;
};

function catchErrorHandler(err, userinfo) {
          var message = "There was an error on this page.\n\n";
          message += "Error description: " + err.description + "\n\n";
          for (var i = 0; i <= userinfo.length; i++) {
                    message += userinfo[i] + "\n\n";
          };
          message += "Click OK to continue.\n\n";
          alert(message);
          return true;
};

// ==============================================================================================================================
// UNIQUE ID
// ==============================================================================================================================

var twoguniqueid = "1";
function getUniqueID() {
          var timeStamp = (new Date).getTime();
          twoguniqueid++
          return "_" + twoguniqueid + "_" + timeStamp;
};

// ==============================================================================================================================
// PUT STORE
// ==============================================================================================================================

function PutIt(putit) {
          // alert("Put: " + putit);
          var x = putStore.length;
          putStore[x] = $("#" + putit).html()
          $("#" + putit).html(x + "||");
};

function GetIt(getit) {
          //  alert("Get: " + getit);
          var x = parseInt(($("#" + getit).html()).replace("|", ""));
          $("#" + getit).html(putStore[x]);
          putStore[x] = "";
};

function ClearIt(clearit) {
          //  alert("Clear: " + clearit);
          var x = parseInt(($("#" + clearit).html()).replace("|", ""));
          $("#" + clearit).html("");
          putStore[x] = "";
};

// ==============================================================================================================================
// HELP
// ==============================================================================================================================

// GET HELP ------------------------------------------------------------------------------------------
function GetHelp(Topic, Location, Parameter1, Parameter2) {
          //Starttime.getDate();
          ws_2g_Core.WSGetHelp(Topic, Location, Parameter1, Parameter2,
                        GetHelp_SucceededCallback, TimeoutCallback, FailedCallback);

};

function GetHelp_SucceededCallback(result) {
          // Show returned content when loaded
          var SectionContent = $get(result.HTMLTarget);
          SectionContent.innerHTML = result.HTMLString;

};

// ==============================================================================================================================
// TEMP STUFF
// ==============================================================================================================================

function InitiateDatePickers() {
          $(function () {
                    var pickerOpts = {
                              showOn: "button",
                              buttonImageOnly: true,
                              dateFormat: "dd-MMM-yy",
                              constrainInput: true,
                              buttonImage: "../Site_Layout/Icons/16/calendar.png"
                    };
                    $("input[id*=Date]").datepicker(pickerOpts);
          });
}

function PageRefresh() {
          //Set auto refresh - Every 30 secs
          rerunrefresh = window.setTimeout("PageRefresh();", 30000);
          //Update ToDo Links Bar (In User Control ucUserServicesLinks1)
          //GetClientUserToDoList();
}



// GET TEST =====================================================================================================
function GetTest(Parameter1, Parameter2) {
          //Starttime.getDate();
          ws_2g_Core.GetTest(Parameter1, Parameter2,
                            GetTest_SucceededCallback, TimeoutCallback, FailedCallback);

};

// GET TEST RESULT
function GetTest_SucceededCallback(result) {
          // Show returned content when loaded
          var SectionContent = $get(result.HTMLTarget);
          SectionContent.innerHTML = result.HTMLString;

};



//// ==============================================================================================================================
//// CATALOGUES
//// ==============================================================================================================================

//  function catalogueListFilter(catalogue,rowcount,sortexpression,searchtext) {
//                //Add the row

//     // LOAD LOCAL DATA SET +++++++++++++++++++++++++++
//                var newlocal = $.grep(localCatalogueContents,function(value) {
//                        var contents = value.split("||"); 
//                        if (contents[1] !== catalogue) {
//                            return  value;
//                        };
//                });
//                
//                var returnqty = 0
//                if (rowcount > newlocal.length) {
//                    returnqty = newlocal.length
//                } else {
//                    returnqty = rowcount
//                };
//                
//                 for (var i=1; i<returnqty; i++) {
//                    var widgetDef = newlocal[i].split("||");
//                             catalogueList(i,widgetDef[0],widgetDef[1],widgetDef[2],widgetDef[3],widgetDef[4],widgetDef[5],widgetDef[6],widgetDef[7],widgetDef[8],widgetDef[9],widgetDef[10],widgetDef[11]);
//                    
//                    };
//    };
//               
//                
//      // CATALOGUE LIST =====================================================================================================
//                function catalogueList(linex,catalogue,GUID,category,itemcode,itemcodeformatted,partnumber,
//                                                    descriptionshort,tradeprice,retailprice,imagepath76,flashmessage) {
//                                                    
//                var cataloguetitle = "Catalogue_" + catalogue;
//                                                    
//                //Add the row
//                $("<tr>").attr( {"id":""+ GUID + ""}).appendTo("#CatalogueContents");
//                $("<td>").appendTo("#" + GUID +"");
//                $("<td>").html(linex).appendTo("#" + GUID +"");
//                $("<td>").html("<img id='image" + GUID +"' src='" + imagepath76 + "'></img>" ).appendTo("#" + GUID +"");
//                $("<td>").html(partnumber ).appendTo("#" + GUID +"");
//                $("<td>").html(category).appendTo("#" + GUID +"");
//                $("<td>").html(itemcodeformatted).appendTo("#" + GUID +"");
//                $("<td>").html(catalogue).appendTo("#" + GUID +"");
//                $("<td>").html(descriptionshort).appendTo("#" + GUID +"");
//                $("<td>").html(linex).appendTo("#" + GUID +"");
//                $("<td>").appendTo("#" + GUID +"");

//                $("#image" + GUID +"").click( function() { alert("XX");
//                
//                
//                
////                $("#" + catalogue + "_detailviewresults div").appendTo("#shopStoredItemDetails");
////                if ($("#shopStoredItemDetails div").is("#ItemDetails_" & itemcode & "") !== true) {
////                    $("<div>").addClass("ui-widget-header").attr("id","ItemDetails_" & itemcode & "").load("Content/ItemDetails.aspx", { "itemCode":"" & itemcode & "" }).appendTo("#" & cataloguetitle & "_detailviewresults");
////                } else {
////                    $("#ItemDetails_" & itemcode & "").appendTo("#" & CatalogueTitle & "_detailviewresults");
////                };
////                if ($("#" & cataloguetitle & "_viewhistory img").is("#ItemImage_" & GUID & "") !== true) {
////                    $("#ItemImage_" & GUID & "").clone().appendTo("#" & CatalogueTitle & "_viewhistory");
////                };
//                $("#" & cataloguetitle & "_detailview").show();
//                $("#" & cataloguetitle & "_results").hide();
////               $("#Catalogue_41611_detailview").show();
////                $("#Catalogue_41611_results").hide();

//          
//                  });
//                  
//};


//// ==============================================================================================================================
//// START ITEM REGISTRATION
//// ==============================================================================================================================

//        // INITIATE REGISTRATION=========================================================================================
//            function InitiateRegistration(TicketID, TicketGUID, SalesDate, Account, UserName) {
//                            //Starttime.getDate();
//                            ws_2g_Core.WSInitiateRegistration(TicketID, TicketGUID, SalesDate, Account, UserName,
//                            InitiateRegistration_SucceededCallback, TimeoutCallback, FailedCallback);
//               
//            };

//            // INITIATE REGISTRATION RESULT
//            function InitiateRegistration_SucceededCallback(result) {
//                    // Show rerror message if failed
//                    if (result.Success == false) { 
//                        ShowDialog("Message","Item Registration - FAILED",result.HTMLString,"");
//                    } else {
//                        ShowDialog("Message","Item Registration - COMPLETE",result.HTMLString,"");
//                    };
//                  
//            };
// 
// ==============================================================================================================================
// START PRINT FORM
// ==============================================================================================================================

//  PRINT FORM
function PrintArea(RegionID, Header, Footer, Title) {

          var destination = $("#PrintDiv1");
          var source = $("#" + RegionID);

          //clear any previous item:
          destination.empty();

          //add Header Content and Footer
          $("<div>").html(Header).addClass("").appendTo(destination);
          source.clone().appendTo(destination);
          $("<div>").html(Footer).addClass("").appendTo(destination);

          //Show dialog:
          var DialogOpts = {
                    title: "<a  href='javascript:PrintFormContent();' title='Print' class='WS1_Linkbutton_Style_0' >" + Title + "</a>",
                    width: 1014,
                    height: 700,
                    zIndex: 5000,
                    modal: true
          };
          //Show the preview dialog
          $("#PrintDialog1").dialog(DialogOpts);
}

// PRINT
function PrintFormContent() {
          $("#PrintDiv1").print();

}
//        
// ==============================================================================================================================
// END PRINT FORM
// ==============================================================================================================================

function printBasket() {
          $("#BasketNotEmptyArea").print();

};

