//domain variable used for doRemoteLoginCheck so that it works on other domains
var domain = "www.micron.com";
var protocol = document.location.protocol;

$(function () {

    // Finger Tabs

    $('.finger-tabs .menu ul li a').hover(
        function () {
            var hoverCat = $(this).parent().attr('class');
            $('.finger-tabs .info div').removeClass('active');
            $('.finger-tabs .info div.' + hoverCat).addClass('active');
        }
    )

    $('.finger-tabs .menu h3').hover(
        function () {
            $('.finger-tabs .info div').removeClass('active');
            $('.finger-tabs .info div.default').addClass('active');
        }
    );

    $('.finger-tabs').mouseleave(
        function () {
            $('.finger-tabs .info div').removeClass('active');
            $('.finger-tabs .info div.default').addClass('active');
        }
    );

    // List for Products Menu
    $('#header #main-bar ul li.products div.subnav-wrapper ul.subnav li.arrowed .category').hover(
    function () {
        $('#header #main-bar ul li.products div.subnav-wrapper ul.subnav li.selectors .list').hide();
        $(this).next().show();
    }
  );

  // Activate Menus
  $('#header #main-bar ul li.toplevel').hover(
    function () {
      $(this).removeClass('active');
      $(this).addClass('active');
      $(this).children('.subnav-wrapper').show();
    },
    function () {
      $(this).children('.subnav-wrapper').hide();
    }
  );

    //PartsTabs.ascx
    // Order Table Tips
    $('#order-table tbody tr').hover(
    function () {
        tipWrapper(this.id);
    }
  );

});


// Start Document Ready Calls
$(document).ready(function () {
    updateFamily();
    //Banner Slider
    $('.bannerslider').flexslider({
        animation: "slide",
        slideshow: true,
        slideshowSpeed: 15000,
        controlNav: true,
        directionNav: false,
        pauseOnHover: true,
        controlsContainer: ".slideNav"
    });

    //Module Slider
    $('.flexslider').flexslider({
        animation: "slide",
        slideshow: false,
        controlNav: false,
        pauseOnHover: true,
        controlsContainer: ".flexslider-container"
    });

    //Rounded Corners for IE6 - IE8
    $(function () {
        if (window.PIE) {
            $('.rounded').each(function () {
                PIE.attach(this);
            });
        }
    });

    //Compare
    //PartsTabs.ascx
    $('#showLB').click(function () {
        $('#compare_overlay').after("<div class=\"overlay\" id=\"comOverlay\" style=\"width: 800px height:800px; opacity:0.8; -ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(opacity=50)\"; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50);\"></div>");
        $('#compare_overlay').show();

        $('#close_overlay').click(function () {
            $('#compare_overlay').hide();
            $('#comOverlay').remove();
        });

        $('#comOverlay').click(function () {
            $('#compare_overlay').hide();
            $('#comOverlay').remove();
        });
    });

    //search
    $("#advanced-search").click(function () {
        $("#advanced-search-box").show();
        return false;
    });

    $("#advanced-search-box .close").click(function () {
        $("#advanced-search-box").hide();
        return false;
    });

    var $mpf = $(".mat-part-found");
    $('#search').blur(function () {
        if ($("#search").val() == "") {
            $mpf.empty();
            autoSuggestOn = false;
        }
        $(".autoSuggestRow").click(function () {
            $("#search").val($(this).text());
            $mpf.hide();
            autoSuggestOn = true;
        });

        $mpf.fadeOut(300);

    });

    $('#search').focus(function () {
        if ($mpf.children().length != 0) {
            $mpf.show();
        }
    });
    getAllParts();
    $('#search').keyup(function (event) {
        if (event.keyCode == 13) {
            submitForm();
        }
        if (event.keyCode == 38) {
            //up arrow
            if ($('.searchSelect').prev().length == 1) {
                $('.searchSelect').removeClass('searchSelect').prev().addClass('searchSelect');
                $("#search").val($('.searchSelect').text());
            }
        } else if (event.keyCode == 40) {
            //down arrow
            if ($('.searchSelect').next().length == 1) {
                $('.searchSelect').removeClass('searchSelect').next().addClass('searchSelect');
                $("#search").val($('.searchSelect').text());
            }
        } else {
            var str = this.value;
            if (str.length < 3) {
                $(".mat-part-found").hide();
                autoSuggestOn = false;
            } else {
                $mpf.empty();
                var k = 0;
                autoSuggestOn = false;
                for (var i = 0; i < JSONdata.length; i++) {
                    if ((JSONdata[i].pn).toLowerCase().search(str.toLowerCase()) != -1 && k < 10 && JSONdata[i].visible == "true") {
                        var urlJSON = "http://" + domain + JSONdata[i].url;
                        var highlightedPart = JSONdata[i].pn;
                        var newPart = highlightedPart.replace(str.toUpperCase(), '<b>' + str.toUpperCase() + '</b>');
                        $mpf.append("<div ref=\"" + urlJSON + "\" class=\"autoSuggestRow \">" + newPart + "</div>");
                        var height = 15 * ($(".mat-part-found").children().length) + "px";
                        $mpf.css("height", height);
                        k++;
                    }
                }
                if (k > 0) {
                    autoSuggestOn = true;
                }
                $mpf.children().eq(0).addClass('searchSelect');
                if ($mpf.children().length != 0) {
                    $mpf.show();
                }

                $('div.autoSuggestRow').mouseover(function () {
                    $('.autoSuggestRow').removeClass('searchSelect');
                    $(this).addClass('searchSelect');
                    $("#search").val($(this).text());

                });
            }
        }
    });
    //end search

});      //end document.ready



//$.getJSON("http://www.micron.com/json/detect-login/?callback=?", updateLoginUI)
//function for navigation webservice
function doRemoteLoginCheck() {
    $.getJSON(protocol + "//" + domain + "/standalone/DetectLogin.aspx?callback=?",
        function (response) {
            var result = response;
            if (result.loggedIn) {
                $("#loginurl").attr("title", result.userFirst + "'s Account");
                $("#loginurl").attr("href", result.loginUrl);
                $("#loginurl").html(result.userFirst + "'s Account");
                $("#signupurl").attr("title", result.userFirst + "'s Account");
                $("#signupurl").attr("href", result.logoutUrl + encodeURIComponent(document.location.href));
                $("#signupurl").html("Logout");
            } else {
                $("#loginurl").attr("title", "Login");
                $("#loginurl").attr("href", result.loginUrl + encodeURIComponent(document.location.href));
                $("#loginurl").html("Login");
                $("#signupurl").attr("title", "Sign up for Access");
                $("#signupurl").attr("href", result.logoutUrl);
                $("#signupurl").html("Sign up for Access");
            }
        },
        function (xhr, status, error) {
            alert(xhr.status);
    });
        
    $("#advanced-search").hide();
}

//search functions
var allParts = [];
var webPartItems = [];
var matPartItems = [];

function textClick(theText,testCase){
	testCase.value = testCase.value == theText ? '' : testCase.value;
}
function textBlur(theText,testCase){
	testCase.value = testCase.value ? testCase.value : theText;
}


function submitForm(){
	if(autoSuggestOn == true){
	    var newURL = $('.searchSelect').attr('ref');
		window.location.href = newURL;
	} 	
	else {
	    var searchCrit = $('#search').val();
	    var newURL = "";
	    for (var i=0; i<JSONdata.length; i++) {
	        if (JSONdata[i].visible == false && JSONdata[i].pn == searchCrit) {
	            newURL = JSONdata[i].url;
	            continue;
	        }
	    }
	    if (newURL == "") {
	        window.location.href = "http://" + domain + "/search?q=" + searchCrit;
		} else {
		    window.location.href = newURL;
		}
	}
}
var JSONdata = "";
function getAllParts() {
    $.ajax({
        url: protocol + "//" + domain + "/assets/js/parts.js",
        type: "GET",
        dataType: "jsonp",
        cache: true,
        ajaxOptions: { cache: true },
        jsonpCallback: "partList"
    });
}

function partList(data) {
    JSONdata = data;
}

var selFam = "";
var selTech = "";
var selAttr = "";
var selURL = "";

function updateFamily() {
    ClearOptions('select.select-family');
    $('select.select-family').append('<option value="0">Select Family<\/option>');
    $('select.select-technology').attr("disabled", "disabled");
    $('select.select-attribute').attr("disabled", "disabled");
    $('select.select-value').attr("disabled", "disabled");
    $.ajax({  // Populate the first field
        url: protocol + "//" + domain + "/assets/js/families.js",
        type: "GET",
        dataType: "jsonp",
        cache: true,
        ajaxOptions: {cache: true},
        jsonpCallback: "famList"
    });
}

function famList(data) {
    var i;
    for (i = 0; i < data.length; i++) {
        $('select.select-family').append('<option>' + data[i].familyName + '<\/option>');
    }
}

function ClearOptions(OptionList) {  // Always clear an option list from the last entry to the first
	$(OptionList).empty();
}

function updateTechnology(familyName) {  //  Populate the second field
	$('select.select-technology').attr("disabled", "disabled");
	$('select.select-attribute').attr("disabled", "disabled");
	$('select.select-value').attr("disabled", "disabled");
	selFam = $('#' + familyName).val();
	if (selFam !== 0) {
	    ClearOptions('select.select-technology');
	    $('select.select-technology').append('<option value="0">Select Technology<\/option>');
		$.ajax({
		    type: "POST",
		    contentType: "application/json; charset=utf-8",
		    url: "/webservices/public/partssearch.asmx/GetTechnologies",
		    data: "{'Family':'" + selFam + "'}",
		    dataType: "json",
		    success: function (response) {
		        var data = eval(response.d);
		        var i;
		        for (i = 0; i < data.length; i++) {
		            $('select.select-technology').append('<option>' + data[i].name + '<\/option>');
		        }
		    }
		});
		$('select.select-technology').removeAttr('disabled');
	}
}

function loadAttrs(technology) {  //  Populate the third field
    $('select.select-attribute').attr("disabled", "disabled");
    $('select.select-value').attr("disabled", "disabled");
    if (technology !== 0) {
        selTech = $('#' + technology).val();
		ClearOptions('select.select-attribute');
		$('select.select-attribute').append('<option value="0">Select Attribute<\/option>');
		$.ajax({
		    type: "POST",
		    contentType: "application/json; charset=utf-8",
		    url: "/webservices/public/partssearch.asmx/GetAttributes",
		    data: "{'Family':'" + selFam + "','Technology':'" + selTech + "'}",
		    dataType: "json",
		    success: function (response) {
		        var data = eval(response.d);
		        var i;
		        for (i = 0; i < data.length; i++) {
		            $('select.select-attribute').append('<option value="' + data[i].Value + '">' + data[i].Text + '<\/option>');
		        }
		    }
		});
		$('select.select-attribute').removeAttr('disabled');
	}
}

function updateValue(attrId){  //  Populate the fourth field
    $('select.select-value').attr("disabled", "disabled");
    if (attrId !== 0) {
        selAttr = $('#' + attrId).val();
		ClearOptions('select.select-value');
		$('select.select-value').append('<option value="0">Select Attr Value<\/option>');
		$.ajax({
		    type: "POST",
		    contentType: "application/json; charset=utf-8",
		    url: "/webservices/public/partssearch.asmx/GetAttributeValues",
		    data: "{'Family':'" + selFam + "','Technology':'" + selTech + "', 'AttributeID':'" + selAttr + "'}",
		    dataType: "json",
		    success: function (response) {
		        var data = eval(response.d);
		        var i;
		        for (i = 0; i < data.length; i++) {
		            $('select.select-value').append('<option>' + data[i].Value + '<\/option>');
		        }
		    }
		});
		$('select.select-value').removeAttr('disabled');
	
	}
}

function buildPartUrl(attrValue) {  // Submit button behaviors
    if (selFam == 0) {
		alert("Please select a Family");
		return false;
	}
    if (selTech == 0) {
		alert("Please select a Technology");
		return false;
    }

    selURL = GetURL();
    if (selURL != "") {
        selURL = selURL.replace("\"", "").replace("\"", "");
    }

    if (selTech !== 0 && selFam !== 0 && selAttr == 0) {
		//selTech = selTech.replace(/\s/g, '-');
        //window.location.href = "/products/" + selFam.toLowerCase() + "/" + selTech.toLowerCase() + "/parts-catalog";
        window.location.href = selURL;
		return false;
    }

    if (attrValue !== 0) {
        //window.location.href = "/products/" + selFam.toLowerCase() + "/" + selTech.toLowerCase() + "/parts-catalog?" + selAttr + "=" + (attrValue - 1);
        window.location.href = selURL + "?&" + selAttr + "=" + (attrValue - 1);
		return false;
	}
	return false;

}

function GetURL() {

    var ReturnURL = "";

    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/webservices/public/partssearch.asmx/GetPartsCatalogURL",
        data: "{'Family':'" + selFam + "','Technology':'" + selTech + "'}",
        dataType: "json",
        success: function (response) {
            ReturnURL = response.d;
        },
        error: function (xhr, status, error) {
            alert(xhr.status);
        }
    });

    return ReturnURL;

}
//end search functions

// Show Tip Wrapper
function showContent(content) {
    var boxContent = $(content).children().children().attr('rel');
    $(boxContent).siblings('div').hide();
    $(boxContent).show();
    if (boxContent == "#order-tab") {
        $('#tip-wrapper').show();
    } else {
        $('#tip-wrapper').hide();
    }
}
function tipWrapper(partNumber) {
    $('#' + partNumber + '_tip').show().siblings().hide();

    if (partNumber == "partNum_0") {
        $('#tip-wrapper').show().css("top", "-11px");
    } else {
        $('#tip-wrapper').show().css("top", "11px");
    }

}

function comparePart(partnum, path, comparenum) {
    $.ajax({
        url: path,
        context: document.body,
        success: function (data) {
            $('#compare_overlay').empty().append(data).css("background-color", "#fff");
        }});
}

function exportgrid(ds, gs, current) {
    url = '/exports/generic-grid.aspx?ds=' + ds + "&gs=" + gs + "&current=" + current;
    location.href = url;
}
