﻿///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////Pageload events///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function loadHome() {
	$('#coda-slider-1').codaSlider({
		autoHeight: false,
		autoSlide: true,
		autoSlideInterval: 6000,
		autoSlideStopWhenClicked: true,
		dynamicArrows: false
	});
	if (!Modernizr.input.placeholder) {
		$('input[placeholder!=""]').hint();
	}
}
function loadusedCar() {
	jQuery('#image-carousel').jcarousel();
	$('#image-carousel img').click(function () {
		fadeImage("vehicle-main-image", $(this)[0].alt);
	});
}
function loadStock() {
	setTabs('true', '');
	$('#tabs li').click(function () {
		setTabs('false', this);
		return false;
	});
	fileUpload('file_upload');
	radioCheckbox("radioFunction");
	$('.jqmWindowMed').jqm();
}
function loadStockList() {
    $('.jqmWindowMed').jqm();
}
function loadAccount() {
    showPassword('ResetPassword');
    $('.jqmWindowMed').jqm();
}
function loadAccountList() {
    $('.jqmWindowMed').jqm();
}
function loadLogin() {
    showPassword('Password_Ctl');
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////Global Functions//////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function fadeImage(Id, src) {
    var a = $("#" + Id);
	$("#" + Id).fadeOut(200, function () {
		$("#" + Id).attr('src', src).bind('readystatechange load', function () {
			if (this.complete) $(this).fadeIn(400);
		});
	});
}
function openPulldown(Id, showTime, outTime) {
	$('#' + Id).stop(true, true).slideDown(showTime).delay(showTime).slideUp(outTime);
}
function openPulldownNoOut(Id, showTime) {
    $('#' + Id).stop(true, true).slideDown(showTime);
}
function slideRemove(Id) {
	$("#" + Id).slideUp("slow", function () { $(this).remove(); });
}
function slideAdd(Id, sHTML) {
    $(sHTML).hide().insertAfter('#' + Id + ' li:first').slideDown("slow");
}
function radioCheckbox(classVal) {
	$("." + classVal).click(function () {
		$("." + classVal + " input[type=checkbox]").each(function () {
			this.checked = false;
		});
		$(this.firstChild).attr('checked', true);
	});
}
function showPassword(Id) {
    $('[id$=' + Id + ']').showPassword('#checker', { text: 'Show Password', name: 'showmypass' });
}
function fileUpload(Id) {
	var sessionid = '';
	$('#' + Id).uploadify({
	    'uploader': '../resources/js/uploadify/uploadify.swf',
	    'script': '../resources/webservices/UploadifyUpload.ashx',
	    'checkScript': '../resources/webservices/UploadifyCheck.ashx?sessionid=' + sessionid,
	    'cancelImg': '../resources/js/uploadify/cancel.png',
	    'folder': '../Docstore',
	    'fileExt': '*.jpg;*.gif;*.png',
	    'fileDesc': 'Image Files (.JPG, .GIF, .PNG)',
	    'multi': true,
	    'auto': true,
	    'removeCompleted': true,
	    'scriptData': { 'sessionid': sessionid },
	    'onCheck': function (event, data, key) {
	        $('#' + Id + key).find('.percentage').text(' - Exists');
	    },
	    'onComplete': function (event, ID, fileObj, response, data) {
	        responseUpload(response);
	        $('#' + Id).uploadifyCancel($('.uploadifyQueueItem').first().attr('id').replace(Id, '')); //This sometimes fails. Still researching a better way.
	    },
	    'onAllComplete': function (event, data) {
	        //Need to slide up all windows, incase something has gone wrong
	    }
	});
}
function addNewProduct() {
    $('#addItem').jqmShow();
}
function addNewAccount() {
    $('#addAccount').jqmShow();
}
function addItem() {
    var DTO = JSON.stringify({ NameAdd: $('[id$=NameAdd] input').val() });
    $.ajax({
        type: "POST",
        url: "./Stock.aspx/AddItem",
        data: DTO,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (j) {
            //var url = location.href.split('?')[0] + '?ID=' + j.d;
            var url = './Stock.aspx?ID=' + j.d;
            window.location = url;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(objXMLHttpRequest.responseText);
        }
    });
}
function addAccount() {
    var DTO = JSON.stringify({ NameAdd: $('[id$=NameAdd] input').val() });
    $.ajax({
        type: "POST",
        url: "./Stock.aspx/AddAccount",
        data: DTO,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (j) {
            var url = './Account.aspx?ID=' + j.d;
            window.location = url;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(objXMLHttpRequest.responseText);
        }
    });
}
function MainStockImageMissing() {
    $("#post-response").attr("class", "topYellow");
    $("#post-response").text("You have not set a main image. Navigate to the image tab and check a box next to an image.");
    $().ready(function () {openPulldownNoOut('prdAdd', 2000) });
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////Page Functions////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function removeImage(Id) {
	if (confirm("Are you sure you want to delete this item? \r\nThis action cannot be undone!")) {
    	var DTO = JSON.stringify({ ID: Id.replace('row', '') });
		//, ProductID: $('[id$=hdnProductID]').val()
    	$.ajax({
    	    type: "POST",
    	    url: "./Stock.aspx/DeleteIMG",
    	    //url: "./Stock/SaveIMG",
    	    data: DTO,
    	    contentType: "application/json; charset=utf-8",
    	    dataType: "json",
    	    success: function (j) {
    	        slideRemove(Id);
    	        if (j.d = "true") {
    	            MainStockImageMissing();
    	        }
    	    },
    	    error: function (XMLHttpRequest, textStatus, errorThrown) {
    	        alert(objXMLHttpRequest.responseText);
    	    }
    	});
		
	}
}
function removeAccount(Id) {
    if (confirm("Are you sure you want to delete this account? \r\nThis action cannot be undone!")) {
        var DTO = JSON.stringify({ ID: Id.replace('row', '') });
        //, ProductID: $('[id$=hdnProductID]').val()
        $.ajax({
            type: "POST",
            url: "./Stock.aspx/DeleteAccount",
            //url: "./Stock/SaveIMG",
            data: DTO,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (j) {
                slideRemove(Id);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(objXMLHttpRequest.responseText);
            }
        });

    }
}
function generateNewLi(i,s) {
    var html = [];
    html.push(
    '<li id="row' + i + '" class="big-row">',
    '<span class="col centre radioFunction"><input id="chkMain' + i + '" type="checkbox" name="chkMain' + i + '" disabled /></span>',
    '<input type="hidden" name="hdnID' + i + '" id="hdnID' + i + '" value="' + i + '" />',
    '<span class="col"><img id="imgProduct' + i + '" src="../Resources/WebServices/ImageHandler.ashx?image=DocStore/' + s + '&width=100&height=100" alt="Product Image" title="Product Image" style=" padding: 6px;" /></span>',
    '<span class="col centre">' + s + '</span>',
    '<a class="col centre" href="javascript:removeImage(\'row' + i + '\');" title="Delete">Delete</a>',
    '<span class="col"></span>',
    '</li>'
    );
    return html.join("");
}
