﻿//Google analytics account information
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-25737324-1']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);

//When the master page loads all function always performed
$(document).ready(function () {
    $(document).ajaxStop($.unblockUI);
    $("button").button();
    $("#radioset").buttonset();
    $("#prodSlideShow").show();

    $('#prodSlideshow').cycle({
        delay: -3000,
        timeout: 4000,
        fx: 'fade',
        prev: '#prev',
        next: '#next',
        pause: true,
        pauseOnPagerHover: true,
        before: function (currSlideElement, nextSlideElement) {

            // Grab the ID of the next li
            var next = $(currSlideElement).next();
            //next = $('#' + next.attr('id'));

            // if the image has not already been loaded
            if (next.find('img').length == 0) {
                // create the img element and insert it in to the li
                var img = $('<img />').attr('src', next.attr('imgsrc'));
                $('#prodSlideShowName').html(next.attr('imgName'));
                $('#prodSlideShowName').attr("prodCode", next.attr('imgCode'));
                next.append(img);
            } else {
                $('#prodSlideShowName').html(next.attr('imgName'));
                $('#prodSlideShowName').attr("prodCode", next.attr('imgCode'));
            }
        }
    });

    //Site Login JQuery Dialog
    $("#lnkLogin").live("click", function () {
        $("#dialog-ProdDetail").dialog('close');
        $("#dialog-Login").dialog('open');
    });

    $("#hshOrganic").click(function () {
        window.location = ProdPath + "Organic-Research-Intermediates";
    });
    $("#hshNMR").click(function () {
        window.location = ProdPath + "NMR-Products";
    });
    $("#hshSilica").click(function () {
        window.location = ProdPath + "Silica-Gels";
    });
    $("#hshBio").click(function () {
        window.location = ProdPath + "Biochemical-Products";
    });
    $("#hshSilanes").click(function () {
        window.location = ProdPath + "Silanes";
    });
    $("#hshSDSLabel").click(function () {
        window.location = InfoPath + "Safety-Data-Sheet-Labelling";
    });

    $(".prodDetailLink").live("click", function () {
        productDetail($(this).attr("prodCode"));
    });

    //Dialog for the site login
    $("#dialog-Login").dialog({
        autoOpen: false,
        resizable: false,
        height: 220,
        width: 350,
        modal: true,
        buttons: {
            "Login": function () {
                DoLogin();
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });



    //Dialog for the product details
    $("#dialog-ProdDetail").dialog({
        autoOpen: false,
        resizable: false,
        height: 500,
        width: 705,
        modal: true,
        close: function (ev, ui) {
            $("#searchStructTop").show();
        },
        buttons: {
            "Close": function () {
                $(this).dialog("close");
            }
        }
    });

    $("#prodSlideShowName").live("click", function () {
        productDetail($(this).attr("prodCode"));
    });

    //Search button on side bar
    $("#btnSearch").live("click", function () {
        ProductSearch();
    });
});

//Logs in
function DoLogin() {
    //Get Company
    var comp = $("#txtCompCode").val();
    //Get User
    var user = $("#txtUsername").val();
    //Get Password
    var pass = $("#txtPassword").val();
    //Check none are blank
    if ($.trim(comp) != "" && $.trim(user) != "" && $.trim(pass) != "") {
        $.ajax({
            cache: false,
            type: "POST",
            url: SysPath + "Login",
            data: JSON.stringify({ comp: comp, username: user, pass: pass }),
            contentType: "application/json",
            dataType: "json",
            success: function (data) {
                LoggedIn(data);
            },
            error: function (xhr, status, error) {
                // you may need to handle me if the json is invalid
                // this is the ajax object
                $("#loginMessage").html("Unable to Login, please try again later.");
            }
        });
    } else {
        $("#loginMessage").html("All fields are required for Login.");
    }
}

//User Logged in
function LoggedIn(data) {
    if (data.ErrorMessage != "") {
        $("#loginMessage").html(data.ErrorMessage);
    } else {
        //Change the account section at top of the page to logged in
        $("#lnkLogin").html("Logged In " + data.LoginName);
        $("#lnkLogin").removeClass("textLink");
        //Close the login Dialog
        $("#dialog-Login").dialog('close');
    }
}

//Logs in
function ProductSearch() {
    //Get Search Type
    var Stype = $("#txtSearchType").val();
    //Get Search Text
    var Stext = $("#txtSearchText").val();
    //Check none are blank
    if ($.trim(Stext) != "") {
        //Submit the form
        $.blockUI({ message: $('#loadingMessage') });
        $("#frmProdSearch").submit();
    }
}

function SetLoading() {
    $("#dialog-ProdDetail").html("<div id='loadingDiv'>Loading...</div>");
}

//Get the product details Ajax will bring back the partial view
function productDetail(prodCode) {
    SetLoading();
    $("#searchStructTop").hide();
    $("#dialog-ProdDetail").dialog('open');
    $.ajax({
        cache: false,
        type: "POST",
        url: ProdPath + "Product-Detail",
        data: JSON.stringify({ prodCode: prodCode }),
        contentType: "application/json",
        dataType: "html",
        success: function (data) {
            //Open the dialog with the html
            $("#dialog-ProdDetail").html(data);
            //Track this in google
            
        },
        error: function (xhr, status, error) {
            // you may need to handle me if the json is invalid
            // this is the ajax object
            alert("error: " + error);
        }
    });
    _gaq.push(['_trackEvent', 'Products', 'Details', prodCode]);
}

//Does a search to webservice then transforms results into table and places in div with title
function doSimpleSearch(type, text, title, divId) {
    //Set box to loading
    $("#" + divId).html("<div id='loadingDiv'>Loading...</div>");
    //Do a simple search ajax
    $.ajax({
        cache: false,
        type: "POST",
        url: ProdPath + "SimpleSearch",
        data: JSON.stringify({ "searchType": type, "searchText": text }),
        contentType: "application/json",
        dataType: "json",
        success: function (data) {
            buildSimpleSearchRes(divId, title, data);
        },
        error: function (xhr, status, error) {
            // you may need to handle me if the json is invalid
            // this is the ajax object
            alert("error retrieving results: " + error);
        }
    });

}

//Build a table for holding the product details
function buildSimpleSearchRes(divId, title, data) {
    htmlString = "";
    if (data.ErrorMessage == null || data.ErrorMessage == "") {

        htmlString = "<h2>" + title + "</h2><table id='tblSearchResultsSm'><tr><th class='col1'>Cat Num</th><th class='col2'>Product Name</th><th class='col3'>CAS</th><th class='col4'>View</th></tr>";

        for (i = 0; i < data.Products.length; i++) {
            htmlString += "<tr><td>" + data.Products[i].Code + "</td>";
            htmlString += "<td>" + data.Products[i].FullName + "</td>";
            htmlString += "<td>" + data.Products[i].CAS + "</td>";
            htmlString += "<td><span class='textLink prodDetailLink' prodcode='" + data.Products[i].Code + "'>View</span></td>";
        }
        htmlString += "</table>";
    } else {
        htmlString = "<h2 class='error'>" + data.ErrorMessage + "</h2>";
    }

    $("#" + divId).html(htmlString);
}


