// JavaScript Document
$(document).ready(function() {
    if ($("#gd").attr("rel") != null) {
        $(".res_p").html('<img src="/images/ac_spinner.gif" />');
        getWPACDataBETA($("#gd").attr("rel"));
    }
    $('.expand').click(function() {
        var ul, span;
        span = $(this);
        ul = span.attr("rel");
        span.toggleClass('collapse');
        $('#' + ul).slideToggle("normal");
    });
    if ($('#col1').length) {
        $("#col1").prepend('<div id="progressbar"></div><div id="custVeh"></div>');
    }
    if ($('#col1_res').length) {
        $("#col1_res").prepend('<div id="progressbar"></div><div id="custVeh"></div>');
    }
    $("#progressbar").progressbar({
        value: 1
    });
    setCartTotal();
    setHeader();
    setCustomerVeh();
    $('#dialog_link, .icons').hover(
	    function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
				);
    $('#btnShAction, .abtn, ul#icons li').hover(
		function() { $(this).addClass('ui-state-hover'); },
		function() { $(this).removeClass('ui-state-hover'); }
	);
    // resolve the icons behavior with event delegation
    $('.gallery, .res_i').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);
        if ($target.is('a.gallery')) {
            viewLargerImage($target);
        } else if ($target.is('span.ui-icon-zoomin')) {
            $target = $target.parent('a');
            viewLargerImage($target);
        } else if ($target.is('img.res_i')) {
            $target = $target.next('a');
            viewLargerImage($target);
        }

        return false;
    });

    $('.tmpMessage').each(function() {
        var to = $(this).attr("rel");
        setTimeout(function() {
            $(".tmpMessage").fadeOut();
        }, to);
    });
});

// image preview function, demonstrating the ui.dialog used as a modal window
function viewLargerImage($link) {
	var src = $link.attr('href');
	var title = $link.prev('img').attr('alt');
	var $modal = $('img[src$="'+src+'"]');

	if ($modal.length) {
		$modal.dialog('open')
	} else {
		var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />').attr('src',src).appendTo('body');
		setTimeout(function() {
			img.dialog({
					title: title,
					width: 656,
					modal: true
				});
		}, 1);
	}
}
function urlPreview(val) {
    var category = '';
    if (val != null) {
        category = val.substring(val.indexOf('|') + 1, val.length) + '/';
        document.getElementById('urlPrevCat').innerHTML = category.toLowerCase();
    }
    else {
        var tmpUrl = document.getElementById('txtURI').value;
        tmpUrl = tmpUrl.replace(" ", "-");
        tmpUrl = tmpUrl.replace(/[^a-zA-Z 0-9_-]+/g, '');
        document.getElementById('txtURI').value = tmpUrl.toLowerCase();
        var tmpS = tmpUrl.toLowerCase() + ".html";
        document.getElementById('urlPrev').innerHTML = tmpS.toLowerCase();
    }
    return;
}
function getWPACDataBETA(str) {
    var params = '{"arr":"' + str + '"}';
    $.ajax({
        type: "POST",
        url: "/wpac_data.asmx/intGet",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            var data;
            data = result.d.split("|");
            for (i = 0; i < data.length; i++) {
                if (data[i] != "") {
                    var _row = data[i].split("~");
                    var div = _row[0];
                    var stockid = div + "_s";
                    var btnid = div + "_a";
                    var qid = div + "_q";
                    var price = _row[1];
                    var stock = _row[2];
                    if (stock == "In-Stock") {
                        //error leave default
                        document.getElementById(div).innerHTML = "$" + price;
                        document.getElementById(stockid).innerHTML = stock;
                    }
                    else {
                        //var qty = stock.substring(stock.indexOf('(') + 1, stock.indexOf(')'));
                        document.getElementById(div).innerHTML = "$" + price;
                        document.getElementById(stockid).innerHTML = stock;
                        if (stock == "Out-Of-Stock") {
                            var abtn = $("#" + btnid);
                            abtn.removeAttr("onclick");
                            abtn.each(function() {
                                this.onclick = function() {
                                    alert('Item Out Of Stock!');
                                };
                            });
                        }
                        //$('#' + qid).attr("name", qty);
                    }

                }
            }
        },
        error: function(xhr, msg, e) {
            //alert(msg + " - getting pricing"); //Error Callback
        }
    });
}
function numbersOnly(tmpS, txtboxid) {
    var txtbox = $("#" + txtboxid);
    tmpS = tmpS.replace(/[^0-9]+/g, '');
    var i = txtbox.attr("name");
    if (parseInt(tmpS) > i) {
        txtbox.val(i);
        alert('Only ' + i + ' In Stock!');
    }
    else {
        txtbox.val(tmpS);
    }
    return;
}
function add(ptn, bid, orp, cor, veh, pnm, qtyid, wgh, bnm) {
    var btnID = qtyid.replace('q', 'a');
    $('#' + btnID).attr("src", "/images/action_wait.gif");

    var strArr, qty, sep;
    sep = '|';
    qty = $("#" + qtyid).val();
    strArr = ptn + sep + bid + sep + orp + sep + cor + sep + veh + sep + pnm + sep + qty + sep + wgh + sep + bnm;
    var params = '{"arr":"' + strArr + '"}';
    $.ajax({
        type: "POST",
        url: "/wpac_data.asmx/add",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            var data;
            data = result.d;
            if (data.substring(0, 3) == "SUC") {
                var dataS = data.split("~");
                var cartTotal, alertM;
                cartTotal = dataS[1];
                alertM = dataS[2];
                $("#cartTotal").html("shopping cart(" + cartTotal + ")");
                $("#page").prepend('<div id="dialog" title="Successfully add part to cart"><p><span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 20px 0;"></span>' + alertM + '</p></div>');
                $("#dialog").dialog({
                    bgiframe: true,
                    modal: true,
                    autoOpen: true,
                    height: 180,
                    width: 600,
                    buttons: {
                    'view cart': function() {
                            window.location = "/cart.aspx";
                        },
                        'Continue Shopping': function() {
                            $(this).dialog('destroy').remove();
                        }
                    }
                });
                $('#' + btnID).attr("src", "/images/action.gif");
            }
            else {
                //Out of stock
                $("#page").prepend('<div id="dialog" title="Out of stock"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + data + '</p></div>');
                $("#dialog").dialog({
                    bgiframe: true,
                    modal: true,
                    autoOpen: true,
                    height: 180,
                    width: 600,
                    buttons: {
                    'close': function() {
                            $(this).dialog('destroy').remove();
                        }
                    }
            });
        }
        },
        error: function(xhr, msg, e) {
            alert(msg); //Error Callback
        }
    });
}
function sendToCart() {
    $('#dialog').fadeOut("slow", function() { $(this).hide(0); });
    $('#dialog-mask').fadeOut("normal", function() { $(this).hide(0); });
    window.location = "/cart.aspx";
}
function setCartTotal(){
    $.ajax({
        type: "POST",
        url: "/wpac_data.asmx/total",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            $("#cartTotal").html('<span class="ui-icon ui-icon-cart"></span>shopping cart(' + result.d + ')');
            $("#cartTotal").attr("style", "display:inline;");
        },
        error: function(xhr, msg, e) {
            $("#cartTotal").html('<span class="ui-icon ui-icon-cart"></span>shopping cart(-)');
            $("#cartTotal").attr("style", "display:inline;");
        }
    });
}
function setHeader(){
    $.ajax({
        type: "POST",
        url: "/wpac_data.asmx/header",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            $("#utils_c").html(result.d);
        }
    });
}
function getYearsForMake() {
    var ddl_year = document.getElementById("ddlyear");
    var ddl_year_text = "";
    ddl_year_text = ddl_year.options[0].text;
    ddl_year.options[0].text = "Loading Years...";
    var mID = $("#ddlmake option:selected").val();
    var params = '{"makeid":"' + mID + '"}';
    $.ajax({
        type: "POST",
        url: "/wpac_data.asmx/years",
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(years) {
            var Years;
            Years = years.d.split("|");
            ddl_year.options.length = 1;
            for (i = 0; i < Years.length; i++) {
                if (Years[i] != "") {
                    ddl_year.options[i + 1] = new Option(Years[i], Years[i]);
                }
            }
            ddl_year.disabled = false;
            ddl_year.options[0].text = ddl_year_text;
        },
        error: function(xhr, msg, e) {
            ddl_year.options[0].text = "Error Loading Years";
        }
    });
}

function actionGo() {
    if ($("#ddlmake option:selected").val() == "NA") {
        alert("Please Select A Make!");
        return;
    }
    else if ($("#ddlyear option:selected").val() == "NA") {
        alert("Please Select A Year!");
        return;
    }
    else {
        var make, year, url;
        make = $("#ddlmake option:selected").html();
        year = $("#ddlyear option:selected").val();
        url = "/" + year + "/" + make.toLowerCase().replace(' ', '') + ".html";
        window.location = url;
    }
}
function setCustomerVeh() {
    var _arr = getCookie('cvehArr');
    if (_arr != null && _arr != "") {
        var _tmpS;
        var _items = null;
        var arr = _arr.split(",");
        for (i = 0; i < arr.length; i++) {
            $("#progressbar").progressbar({
                value: 100 / i
            });
            if (arr[i] != "") {
                if (_items != null) {
                    _items += setVehListItem(arr[i]);
                }
                else {
                    _items = setVehListItem(arr[i]);
                }
            }

        }
        _tmpS = '<ul>' + _items + '</ul><br />&nbsp;<a style="margin:0 0 0 0; padding:0 0 0 0; background:none;" href="javascript:void(0)" onclick="javascript:confirmDeleteAll()">Remove Vehicle(s)</a>';
        $("#progressbar").remove();
        $('#custVeh').html(_tmpS);
        $('#custVeh').addClass('custVehC ui-corner-bottom');
        if ($('#custCehHeader').length) {
            $('#custVeh').before('<div id="custCehHeader"class="ui-state-default ui-corner-top lheader"><span class="ui-icon ui-icon-person"></span>My Vehicles</div>');
        }

    }
    else {
        $("#progressbar").remove();
    }
}
function entryDeleteAlert(value) {
    if (value == 'delete') {
        $("#page").prepend('<div id="dialog" title="Confirm Delete"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Please note that when you press "GO" you will permanently delete this entry.</p></div>');
        $("#dialog").dialog({
            bgiframe: true,
            modal: true,
            autoOpen: true,
            height: 180,
            width: 600,
            buttons: {
                'OK': function() {
                    $(this).dialog('destroy').remove();
                }
            }
        });
    }
}
function deleteVeh(id) {
    $("#page").prepend('<div id="dialog" title="Confirm Delete"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want do delete this vehicle?</p></div>');
    $("#dialog").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: true,
        height: 180,
        width: 600,
        buttons: {
            'delete': function() {
                deleteVehAction(id);
                $(this).dialog('destroy').remove();
            },
            'cancel': function() {
                $(this).dialog('destroy').remove();
            }
        }
    });
}
function confirmDeleteAll() {
    $("#page").prepend('<div id="dialog" title="Confirm Delete"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure you want to delete all vehicle(s)?</p></div>');
    $("#dialog").dialog({
        bgiframe: true,
        modal: true,
        autoOpen: true,
        height: 180,
        width: 600,
        buttons: {
            'delete': function() {
                deleteVehs();
                $(this).dialog('destroy').remove();
            },
            'cancel': function() {
                $(this).dialog('destroy').remove();
            }
        }
    });
}
function setVehListItem(str) {
    var arr = str.split("~");
    return '<li><a href="' + arr[0] + '">' + arr[1] + '</a> <a href="javascript:void(0)" onclick="javascript:deleteVeh(\'' + str + '\')"><span class="ui-icon ui-icon-squaresmall-close ui-state-default ui-corner-all icons" style="cursor:pointer;display:inline;position:absolute;margin:0 0 5px 3px"></span></a></li>';
}

function addCustomerVeh(veh, url) {
    var _arr = getCookie('cvehArr');
    if (_arr != null && _arr != "") {
        if (_arr.indexOf(url) == -1) {
            _arr = _arr + "," + url + "~" + veh;
            deleteVehs();
            setCookie('cvehArr', _arr, 365);
        }
    }
    else {
        _arr = url + "~" + veh;
        setCookie('cvehArr', _arr, 365);
    }
}
function deleteVehs() {
    setCookie('cvehArr', null, -1);
    $('#custVeh').removeClass('custVehC');
    $('#custVeh').html("");
    $('#custCehHeader').remove();
}

function deleteVehAction(id) {
    var _veh = getCookie('cvehArr');
    var _arr = _veh.split(",");
    for (i = 0; i < _arr.length; i++) {
        if (id == _arr[i]) {
            _arr.splice(i, 1);
        }
    }
    if (_arr.length > 0) {
        setCookie('cvehArr', _arr, 365);
        setCustomerVeh();
    }
    else {
        deleteVehs();
    }
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    var path = "/";
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString()) + "; path=" + escape(path);
}