﻿
// Global var --------------------------------------------------------------------------------------

var mouseX = 0;
var mouseY = 0;

// jQuery center div -------------------------------------------------------------------------------------------

jQuery.fn.center = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}


// Page
function aLoadTop() { $('html, body').scrollTop(0); }
function aSlideTop() { jQuery('html, body').animate({ scrollTop: 0 }, 'fast'); }


// aClose -------------------------------------------------------------------------------------------

function aClose(div) { $('#' + div).css('visibility', 'hidden'); }
function aCloseHeight(div) { $('#' + div).css('visibility', 'hidden'); $('#' + div).css('height', '0px'); }
function aShow(div) { $('#' + div).css('visibility', 'inherit'); }
function aHtmlInput(div, divInput) { $('#' + div).html(divInput); }
function aDisableForm(div) { $('#' + div).attr("disabled", "disabled"); }
function aEnableForm(div) { $('#' + div).attr("disabled", ""); }


function aShowHide(div, action, height) {
    $('#' + div).css('visibility', action);
    $('#' + div).css('height', height);
}

function aCloseAndEmpty(div, divEmpty) {

    $('#' + div).css('visibility', 'hidden');
    $('#' + divEmpty).html('');

}

function aCloseAndClear(div) {

    $('#' + div).css('visibility', 'hidden');
    $('#' + div).html('');
    //$('#' + div).css('height', '0px');

}

function aShowHtmlInput(showDiv, targetDiv, divInput) {

    $('#' + showDiv).css('visibility', 'inherit');
    $('#' + targetDiv).html(divInput); 

}



// Validate ----------------------------------------------------------------------------------------

function aValidateEmailAddress(emailAddress) {  

    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);  
    return pattern.test(emailAddress);

}

function aValidateIsNumeric(strString, strValidChars)
//  check for valid numeric strings	
{
    //var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;

    if (strString.length == 0) return false;

    //  test strString consists of valid characters listed above
    for (var i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}



// Valiation ---------------------------------------------------------------------------------------

function inlineValidate(divName, validateTyp, validateValue, innerCallBackPanel, typeCallback) {

    var returnThis = false;

    if (validateTyp == "email") {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        returnThis = pattern.test(($('#' + divName).val()));
    }

    if (validateTyp == "minInput" || validateTyp == "minInputNumeric") {
        if (($('#' + divName).val()).length >= validateValue) {
            returnThis = true;
            if (typeCallback == "singleCallback") {
                aClose(innerCallBackPanel);
            }
        }
    }

    if (validateTyp == "equals") {
        if ($('#' + divName).val() == $('#' + validateValue).val()) {
            returnThis = true;
            if (typeCallback == "singleCallback") {
                aClose(innerCallBackPanel);
            }
        }
    }

    return returnThis;
}

// aLoad -------------------------------------------------------------------------------------------

// AJAX load function
// div: anger vilken div som skall ta emot HTML response
// icon: id namn på AJAX icon som skall visas
// url: AJAX request destination. Ex ajax.apsx
// qString: QueryString till url
// HTML response sker endast från div id=aReturn
// Exempel: onclick="javascript:aLoad('Return1','icon1','aLoad_ajax.aspx','&id1=1&id2=2'); return false;"

function aLoad(div, icon, url, qString, loadFunc, showStatus) {
    var random = parseInt(Math.random()*999999999999999);
    
    $('#' + icon).css('visibility', 'visible');
    $('#' + div).load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function (response, status, xhr) {
        if (xhr.status == "200") {
            $('#' + icon).css('visibility', 'hidden');
            eval(loadFunc);
        }
        if (showStatus == 1) {
            if (status == "error") {
                alert("Ett server fel har uppstått. Kontrollera inmatad data!");
            }
        }
    });
}

// Test används endast på edit artikel
function aLoad2(div, icon, url, qString, div2, icon2, url2, qString2, loadFunc) {
    var random = parseInt(Math.random() * 999999999999999); var runOnce1 = 0; var runOnce2 = 0;

    $('#' + icon).css('visibility', 'visible');
    $('#' + div).load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function () {
        $('#' + icon).css('visibility', 'hidden');
    });

    $('#' + div2).load(url2 + '?random=' + random + '&div=' + div2 + qString2 + ' #aReturn', function (response, status, xhr) {
        if (xhr.status == "200") {
            $('#' + icon2).css('visibility', 'hidden');
            //alert(xhr.statusText);
            //eval(loadFunc);
        }   
    });
}

function aLoadRead(div, icon, url, aInput, callBackPanel, qString, loadFunc) {

    var random = parseInt(Math.random() * 999999999999999);
    aClose(callBackPanel);
    var validatePass = true; var validatePassCustom = false; var validatePassGlobal = true;
    // aInput ----------------------------------------------------------------------------------------
    var data = ""; var aInputResult = aInput.split("#");
    for (var i = 0; i < aInputResult.length; i++) {
        var x; x = aInputResult[i].split("!");
        if (x[0] == "text") { data = data + "&" + x[1] + "=" + encodeURIComponent($('#' + x[2]).val()); }
        if (x[0] == "radiobutton") { data = data + "&" + x[1] + "=" + encodeURIComponent($("input[name='" + x[2] + "']:checked").val()); }

        // Validate, minimum input med callback om false
        if (x[3] == "minInput") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate minimum input med INGEN callback om false
        // Inget sker innan minimi input true
        if (x[3] == "minInputNoAction") {
            validatePass = false;
            if (($('#' + x[2]).val()).length >= x[4]) { validatePassCustom = aValidateIsNumeric(($('#' + x[2]).val()), '0123456789'); }
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                validatePassGlobal = false;
                //break;
            }
        }
    }

    // + qString data 
    data = data + qString

    // aOutput ---------------------------------------------------------------------------------------
    if (validatePass == true) { aLoad(div, icon, url, data) }
    if (validatePassCustom == true) { eval(loadFunc); }

}

function aLoadReadV2(div, icon, url, aInput, callBackPanel, qString, loadFunc) {

    var random = parseInt(Math.random() * 999999999999999);
    aClose(callBackPanel);
    var validatePass = true; var validatePassGlobal = true;
    // aInput ----------------------------------------------------------------------------------------
    var data = ""; var aInputResult = aInput.split("#");
    for (var i = 0; i < aInputResult.length; i++) {
        var x; x = aInputResult[i].split("!");
        if (x[0] == "text") { data = data + "&" + x[1] + "=" + encodeURIComponent($('#' + x[2]).val()); }
        if (x[0] == "radiobutton") { data = data + "&" + x[1] + "=" + encodeURIComponent($("input[name='" + x[2] + "']:checked").val()); }
        if (x[0] == "checkbox") { data = data + "&" + x[1] + "=" + encodeURIComponent(($('#' + x[2]).is(':checked')) ? 1 : 0); }

        // Validate
        if (x[3] == "minInput") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "minInputNumeric") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == true) { validatePass = aValidateIsNumeric(($('#' + x[2]).val()), '0123456789'); }
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "email") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "equals") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Load function
        if (x[3] == "loadFunc") {

            eval(x[4]);
        }

        // Validate minimum input med INGEN callback om false
        // Inget sker innan minimi input true
        if (x[3] == "minInputNoAction") {
            validatePass = false;
            if (($('#' + x[2]).val()).length >= x[4]) { validatePass = aValidateIsNumeric(($('#' + x[2]).val()), '0123456789'); }
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                validatePassGlobal = false;
                //break;
            }
        }
    }

    // + qString data 
    data = data + qString

    // aOutput ---------------------------------------------------------------------------------------
    if (validatePass == true) {
        aLoad(div, icon, url, data);
        eval(loadFunc);
    }
}

function aLoadJsonRead(icon, url, type, aInput, callBackPanel, qString) {

    var random = parseInt(Math.random() * 999999999999999);
    aClose(callBackPanel);
    var validatePass = true; var validatePassGlobal = true;
    // aInput ----------------------------------------------------------------------------------------
    var data = ""; var aInputResult = aInput.split("#");
    for (var i = 0; i < aInputResult.length; i++) {
        var x; x = aInputResult[i].split("!");
        if (x[0] == "text") { data = data + "&" + x[1] + "=" + encodeURIComponent($('#' + x[2]).val()); }
        if (x[0] == "radiobutton") { data = data + "&" + x[1] + "=" + encodeURIComponent($("input[name='" + x[2] + "']:checked").val()); }
        if (x[0] == "checkbox") { data = data + "&" + x[1] + "=" + encodeURIComponent(($('#' + x[2]).is(':checked')) ? 1 : 0); }

        // Validate
        if (x[3] == "minInput") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "minInputNumeric") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == true) { validatePass = aValidateIsNumeric(($('#' + x[2]).val()), '0123456789'); } 
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "email") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Validate
        if (x[3] == "equals") {
            validatePass = false;
            validatePass = inlineValidate(x[2], x[3], x[4], x[5], x[8]);
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                callBack_error(x[5], x[6], x[7]);
                validatePassGlobal = false;
                //break;
            }
        }

        // Load function
        if (x[3] == "loadFunc") {

            eval(x[4]);
        }

        // Validate minimum input med INGEN callback om false
        // Inget sker innan minimi input true
        if (x[3] == "minInputNoAction") {
            validatePass = false;
            if (($('#' + x[2]).val()).length >= x[4]) { validatePass = aValidateIsNumeric(($('#' + x[2]).val()), '0123456789'); }
            if (validatePass == false) { //alert(x[5] + " | " + x[6] + " | " + x[7]);
                validatePassGlobal = false;
                //break;
            }
        }
    }

    // + qString data 
    data = data + qString
    
    // aOutput ---------------------------------------------------------------------------------------
    if (validatePassGlobal == true) {

    //alert(icon, url, type, data);
    aPostJsonData(icon, url, type, data);
    }

}

function aLoadnoIcon(div, url, qString) {
    var random = parseInt(Math.random() * 999999999999999);
    //$('#icon').hide(); //$('#icon').show(); //$('#'+icon).css('visibility', 'visible'); //$('#'+icon).css('visibility', 'hidden');$('#' + icon).attr("src", "../_bilder/animering/icon.gif");    $('#'+icon).attr( "src", "../_bilder/animering/empty.png"); 

    $('#' + div).load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function () { });
}

function aLoadSlide(div, icon, url, qString) {
    var random = parseInt(Math.random() * 999999999999999);
    //$('#icon').hide(); //$('#icon').show(); //$('#'+icon).css('visibility', 'visible'); //$('#'+icon).css('visibility', 'hidden');$('#' + icon).attr("src", "../_bilder/animering/icon.gif");    $('#'+icon).attr( "src", "../_bilder/animering/empty.png"); 

    $('#' + icon).css('visibility', 'visible');
    //$('#' + div).load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function() {
    //    $('#' + icon).css('visibility', 'hidden');
    //});

    $('#' + div).slideDown("slow").load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function() {
        $('#' + icon).css('visibility', 'hidden');
    });


}
// aLoad x2 -------------------------------------------------------------------------------------------

// Samma som ovan fast 2 AJAX request
// Exempel: onclick="javascript:aLoadx2('Return1','icon1','aLoad_ajax.aspx','&id1=1&id2=2','Return2','icon2','aLoad2_ajax.aspx','&id1=3&id2=4'); return false;"

var aLoadx2 = function(div, icon, url, qString, div2, icon2, url2, qString2) { 
    var random = parseInt(Math.random()*999999999999999);
    

    // HTMl output 1
    $('#' + div).load(url + '?random=' + random + '&div=' + div + qString + ' #aReturn', function() {
        $('#' + icon).css('visibility', 'hidden');
    });
    // HTMl output 2
    $('#' + div2).load(url2 + '?random=' + random + '&div=' + div2 + qString2 + ' #aReturn', function() {
        $('#' + icon2).css('visibility', 'hidden');
    });

    // Visar AJAX icon
    $('#' + icon).css('visibility', 'visible');
    $('#' + icon2).css('visibility', 'visible');
}

// aClickMouse -------------------------------------------------------------------------------------------

function aMousePosistion() {

    $(document).click(function(e) {
        //$('#status').html(e.pageX + ', ' + e.pageY);
        //alert(e.pageX + ', ' + e.pageY);
        mouseX = e.pageX;
        mouseY = e.pageY;

        //$('#editAdminHolder').css('top', adjustY);
        //$('#editAdminHolder').css('left', adjustX);

        //$('#editAdminHolder').css('visibility', 'visible');
    });
}


// aLoadBox -------------------------------------------------------------------------------------------

// AJAX load function
// div: anger vilken div som skall ta emot HTML response
// icon: id namn på AJAX icon som skall visas
// url: AJAX request destination. Ex ajax.apsx
// qString: QueryString till url
// HTML response sker endast från div id=aReturn
// Exempel: onclick="javascript:aLoadBox('Return1','icon1','aLoad_ajax.aspx','&id1=1&id2=2','box1','200','Rubrik'); return false;"

function aLoadBox(div, icon, url, qString, boxID, boxWidth, boxName) {

    aLoad(div, icon, url, qString);

    var adjustX = mouseX - boxWidth/2;
    var adjustY = mouseY;

    $('#' + boxID).dialog('option', 'width', +boxWidth);
    $('#' + boxID).dialog('option', 'title', boxName);
    //$('#' + boxID).dialog('option', 'transfer', 'slow');
    $("#" + boxID).dialog('option', 'position', [adjustX, adjustY]);

    //$('#' + boxID).effect("transfer", { to: $('#' + boxID) }, 1000); 
    
    //var options = { to: "#pnl_vktop" };
    //$("#" + boxID).show('transfer', options, '500');

    //$('#' + boxID).dialog('option', 'show', 'transfer', options, 500);
    
    //show(effect, [options], [speed], [callback])
    //$('#' + boxID).dialog('option', 'show', 'slide');
    //$('#' + boxID).dialog({ position: 'top' });
    //$('#' + boxID).dialog('option', 'position', 'top');
    //$('#' + boxID).effect('transfer', { to: '#pMenu' }, 'slow');
    //$('#' + boxID).show("clip", { direction: "horizontal" }, 500);
    //$(".box").effect("transfer",{to:"h1.logo a"},"slow")"
    //$('#' + boxID).effect('transfer', { to: '#pMenu' }, 'slow'); 
    //$('#' + boxID).dialog({ show: 'slide' });
    $('#' + boxID).dialog('open');
}
// aPost -------------------------------------------------------------------------------------------

// AJAX post formulär funktion
// div: anger vilken div som skall ta emot HTML response
// icon: id namn på AJAX icon som skall visas
// url: AJAX request destination. Ex ajax.apsx
// type: POST eller GET
// data: Formulär fältnamn, laddas från aPostName()
// loadFunc: startar en funktion efter avslutad aPost

function aPost(div, icon, url, type, data, loadFunc) {
    
	//disabled all the text fields
	//$('.text').attr('disabled','true');
	
	//show the loading sign
	$('#' + icon).css('visibility', 'visible');
	
	//start the ajax
	$.ajax({
	
		//this is the php file that processes the data and send mail
	    url: url,	
		
		//GET method is used
	    type: type,

		//pass the data
	    data: data,		
		
		//Do not cache the page
		cache: false,
		
		//success
		success: function (html) {	
		    
		    // HTMl output
		    $('#' + div).html(html);
		    $('#' + icon).css('visibility', 'hidden');

		    // Startar funktion
		    eval(loadFunc);
		}	
	});
}

function aPostJson(icon, url, type, data) {

    var random = parseInt(Math.random() * 999999999999999);
    data = "random=" + random + data;

    //disabled all the text fields
    //$('.text').attr('disabled','true');

    //show the loading sign
    $('#' + icon).css('visibility', 'visible');

    //start the ajax
    $.ajax({

        //this is the php file that processes the data and send mail
        url: url,

        //GET method is used
        type: type,

        //pass the data
        data: data,

        //data type
        dataType: 'json',

        //Do not cache the page
        cache: false,

        //success
        success: function(json) {

            // HTMl output
            if (json.success) {
                //Call the function
                eval(json.loadFunction);

            } else {

                //Call the function
                eval(json.loadFunction);
            }


            $('#' + icon).css('visibility', 'hidden');
        }
    });
}

function aPostJsonData(icon, url, type, data) {

    var random = parseInt(Math.random() * 999999999999999);
    data = "random=" + random + data;

    //show the loading sign
    $('#' + icon).css('visibility', 'visible');

    //start the ajax
    $.ajax({

        //this is the php file that processes the data and send mail
        url: url,

        //GET method is used
        type: type,

        //pass the data
        data: data,

        //data type
        dataType: 'json',

        //Do not cache the page
        cache: false,

        //success
        success: function (json) {

            // HTMl output
            if (json.success) {
                //Call the function
                eval(json.loadFunction);

                $('#' + icon).css('visibility', 'hidden');

            } else {

                //Call the function
                eval(json.loadFunction);

                $('#' + icon).css('visibility', 'hidden');
            }


            
        }
    });
}

function callBack_error(callBackPanel, callBackLabel, callBackText) {

    //Visa callBackPanel
    $('#' + callBackPanel).css('visibility', 'visible');
    $('#' + callBackLabel).text(callBackText);

}

function callBack_error_Visible(callBackLabel, callBackText) {

    //Visa callBackPanel
    $('#' + callBackLabel).text(callBackText);

}

function aPostRedirect(div, icon, url, type, data, redirectURL) {

    //disabled all the text fields
    //$('.text').attr('disabled','true');

    //show the loading sign
    $('#' + icon).css('visibility', 'visible');

    //start the ajax
    $.ajax({

        //this is the php file that processes the data and send mail
        url: url,

        //GET method is used
        type: type,

        //pass the data
        data: data,

        //Do not cache the page
        cache: false,

        //success
        success: function(html) {

            // HTMl output
            //$('#' + div).html(html);
            //$('#' + icon).css('visibility', 'hidden');
            self.location = redirectURL;
        }
    });
}

// aPost anrop -------------------------------------------------------------------------------------------

// AJAX post formulär funktion
// div: anger vilken div som skall ta emot HTML response
// icon: id namn på AJAX icon som skall visas
// url: AJAX request destination. Ex ajax.apsx
// type: POST eller GET
// text1: Formulär fält, ex. id="text1"
function aPostName(div, icon, url, type) {

    //Get the data from all the fields
    //var text1 = encodeURIComponent($('input[id=Text1]').val());
    var text1 = encodeURIComponent($('#Text1').val());
    var text2 = encodeURIComponent($('input[id=Text2]').val());
    var text3 = encodeURIComponent($('input[id=Text3]').val());
    //var select1 = $('select[id=Select1]').val();
    var select1 = $('#Select1').val();
    var select1_text = $('#Select1 :selected').text();

    var checkbox1 = ($('#Checkbox1').is(':checked')) ? $('#Checkbox1').val():0;
    
    var radio1 = 0;
    if ($('#Radio1').is(':checked')) { radio1 = $('#Radio1').val(); }
    if ($('#Radio2').is(':checked')) { radio1 = $('#Radio2').val(); }
    if ($('#Radio3').is(':checked')) { radio1 = $('#Radio3').val(); }
    
    //organize the data properly
    var data = 'text1=' + text1 + '&text2=' + text2 + '&select1=' + select1 + '&checkbox1=' + checkbox1 + '&radio1=' + radio1 + '&text3=' + text3;

    //var data = 'text1=' + text1.val() + '&text2=' + text2.val() + '&text3=' + encodeURIComponent(text3.val());		

    //alert(data);

    // Anropar AJAX funktion, aPost
    aPost(div, icon, url, type, data);
}


function alertReturn4() {
		var text1 = encodeURIComponent($('textarea[id=Return4]').val());
		alert(text1);
}

// Replace to punkt ------------------------------------------------------------
function replaceKomma(formValue) {
    return formValue.replace(/,/, ".");
}
