﻿function fireOnchange(elementId) {
    var txt = document.getElementById(elementId)

    //On Gecko based browsers
    if (document.createEvent) {
        var evt = document.createEvent('HTMLEvents');
        if (evt.initEvent) {
            evt.initEvent('change', true, true);
        }
        if (txt.dispatchEvent) {
            txt.dispatchEvent(evt);
        }
    } else {
        //On IE
        //if (myObject.onchange) { // IE
        var newEvt = document.createEventObject();
        txt.fireEvent("onchange", newEvt);
        //}
    }
}

String.prototype.startsWith = function(str)
{ return (this.match("^" + str) == str) }

String.prototype.endsWith = function(str)
{ return (this.match(str + "$") == str) }

String.prototype.contains = function(str)
{ return (this.indexOf(str) >= 0) }

String.prototype.trim = function()
{ return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")) }

function clearRadioButton(rblTable) {
    if (rblTable){
        for (var count = 0; count < rblTable.rows.length; count++) {
            if (rblTable.rows[count].cells[0].getElementsByTagName('input').length > 0) {
                var rbn = rblTable.rows[count].cells[0].getElementsByTagName('input')[0];
                if (rbn != null) {
                    if (rbn.checked == true) {
                        rbn.checked = false;

                    }
                }
            }
        }
    }
}

function isKeyPressReturn(e) {
    var charCode;

    if (e && e.which) {
        charCode = e.which;
    } else if (window.event) {
        e = window.event;
        charCode = e.keyCode;
    }

    if (charCode == 13) {
        return true;
    }
    return false;
}


function printDateTime(date) {
    return printDate(date) + " " + printTime(date);
}

function printDate(date) {
    var d = date.getDate();
    var day = (d < 10) ? '0' + d : d;
    var m = date.getMonth() + 1;
    var month = (m < 10) ? '0' + m : m;
    var yy = date.getYear();
    var year = (yy < 1000) ? yy + 1900 : yy;

    switch (getLanguageId()) {
        default:
        case 1: //FR
            return day + '/' + month + '/' + year;
        case 2: //EN
            return month + '/' + day + '/' + year;
    }
}

function printTime(date) {
    var h = date.getHours();
    var hours = (h < 10) ? '0' + h : h;
    var m = date.getMinutes();
    var minutes = (m < 10) ? '0' + m : m;
    var s = date.getSeconds();
    var seconds = (s < 10) ? '0' + s : s;

    switch (getLanguageId()) {
        default:
        case 1: //FR
            return hours + ':' + minutes + ':' + seconds;
        case 2: //EN
            return (hours > 12 ? hours - 12 : hours) + ':' + minutes + ':' + seconds + ' '(hours > 12 ? 'PM' : 'AM');
    }
}


///////////////////////PACKAGE FROM VALIDATOR/////////////////////////

function validatePackageDate(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var array = arguments.Value.split('/');
        var myDate;

        if (array[0].length > 1 && array[0].startsWith('0'))
            array[0] = array[0].substr(1, 2);
        if (array[1].length > 1 && array[1].startsWith('0'))
            array[1] = array[1].substr(1, 2);
        if (array[2].length > 1 && array[2].startsWith('0'))
            array[2] = array[2].substr(1, 2);

        if (array.length == 3) {
            switch (getLanguageId()) {
                default:
                case 1: //FR
                    myDate = new Date(parseInt(array[2]), parseInt(array[1]) - 1, parseInt(array[0]));
                    break;
                case 2: //EN
                    myDate = new Date(parseInt(array[2]), parseInt(array[0]) - 1, parseInt(array[1]));
                    break;
            }

            today = new Date();

            if (myDate <= today) {
                arguments.IsValid = true;
                return true;
            } else {
                arguments.IsValid = false;
                return false;
            }
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

///////////////////////////////////////////////////////////////////



///////////////////////////ADDRESS ////////////////////////////////

function getZoomFromAccuracy(accuracy) {
    var tabZoom = new Array(2, 4, 6, 10, 12, 13, 16, 16, 17, 18);
    return tabZoom[accuracy];
}

///////////////////////////////////////////////////////////////////



///////////////////////USER FROM VALIDATOR/////////////////////////

function validateEmail(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validatePassword(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^.{6,}/gi);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validateUsername(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 5)) {
        arguments.IsValid = false;
        return false;
    } else {
        var regex = new RegExp(/^([a-zA-Z0-9_\.\-])+$/gi);
        if (regex.test(arguments.Value)) {
            arguments.IsValid = true;
            return true;
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

function validateBirthdate(source, arguments) {
    if ((arguments.Value == null) || (arguments.Value.length <= 0)) {
        arguments.IsValid = false;
        return false;
    } else {
        var array = arguments.Value.split('/');
        var myDate;

        if (array[0].length > 1 && array[0].startsWith('0'))
            array[0] = array[0].substr(1, 2);
        if (array[1].length > 1 && array[1].startsWith('0'))
            array[1] = array[1].substr(1, 2);
        if (array[2].length > 1 && array[2].startsWith('0'))
            array[2] = array[2].substr(1, 2);

        if (array.length == 3) {
            switch (getLanguageId()) {
                default:
                case 1: //FR
                    myDate = new Date(parseInt(array[2]), parseInt(array[1]) - 1, parseInt(array[0]));
                    break;
                case 2: //EN
                    myDate = new Date(parseInt(array[2]), parseInt(array[0]) - 1, parseInt(array[1]));
                    break;
            }

            today = new Date();
            today.setDate(new Date().getDate() - 1);

            if (myDate < today) {
                arguments.IsValid = true;
                return true;
            } else {
                arguments.IsValid = false;
                return false;
            }
        } else {
            arguments.IsValid = false;
            return false;
        }
    }
}

var userExists = false;
function validateUserExists(source, arguments) {
    if (userExists) {
        arguments.IsValid = false;
        return false;
    } else {
        arguments.IsValid = true;
        return true;
    }
}




///////////////////////////////////////////////////




///////////////////////AJAX////////////////////////

var xmlHttp = getNewHTTPObject();

function getNewHTTPObject() {
    var xmlhttp;
    /** Special IE only code ... */
    /*@cc_on
    @if (@_jscript_version >= 5)
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E) {
            xmlhttp = false;
        }
    }
    @else
             xmlhttp = false;
        @end
    @*/

    /** Every other browser on the planet */
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e) {
            xmlhttp = false;
        }
    }

    return xmlhttp;
}

function doAjaxRequest(url, data, callback, isJSON) {
    try {
        xmlHttp = getNewHTTPObject();
        xmlHttp.open('POST', url, true);
        xmlHttp.onreadystatechange = function() {
            if (self.xmlHttp.readyState == 4) {
                var response = '';
                if (isJSON) {
                    var jsonStr = self.xmlHttp.responseText;
                    var json = eval("(" + jsonStr + ')')
                    if (json && json.d)
                        response = json.d;
                    else
                        response = self.xmlHttp.responseText;
                } else {
                    var xmlDoc = self.xmlHttp.responseXML;
                    if (xmlDoc) {
                        var responseElement = xmlDoc.getElementsByTagName("string")[0];
                        if (responseElement && responseElement.firstChild) {
                            response = responseElement.firstChild.nodeValue;
                        } else {
                            response = self.xmlHttp.responseText;
                        }
                    } else {
                        response = self.xmlHttp.responseText;
                    }
                }
                eval(callback + "('" + response + "');");
            }
        }
        if (isJSON)
            xmlHttp.setRequestHeader('Content-Type', 'application/json');
        else
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlHttp.send(data);
    } catch (E) {
    }
}


///////////////////////////////////////////////////






///////////////// Keywords jQuery//////////////////
//Word Selector = WS
var _IsActivated = false;
var _sIdDivContainer_WS;
var _sIdTxt_WS;
var _idHdnValues;
var _sIdTxtMover_WS = "_txtWordSelectorMover";
var _sIdDivWordSelectedContainer_WS = "_divWordSelectedContainer";
var _sIdLblInfo_WS = "_lblInfo";

//**INIT**************************************************************************************
function InitKeywordsFieldValues(FieldId, HdnId, containerId) {
    _IsActivated = true;
    _sIdTxt_WS = FieldId;
    _idHdnValues = HdnId;
    _sIdDivContainer_WS = containerId;
    _sIdTxtMover_WS = "_txtWordSelectorMover";
    _sIdDivWordSelectedContainer_WS = "_divWordSelectedContainer";
    _sIdLblInfo_WS = "_lblInfo";
}
function InitWordSelector_WS() {
    if (_IsActivated) InitWordSelectorBegin_WS();
}
function InitWordSelectorBegin_WS() {
    //Label
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).hide();
}
//**ONEVENT***********************************************************************************
function OnTxtChanged_WS() {
    if (_IsActivated) CheckStringSpecialEntered_WS();
}
function OnStringSpecialEntered_WS(sWord) {
    if (_IsActivated) {
        //1)Prevent entering words
        jQuery("#" + _sIdTxt_WS).attr("readonly", "readonly");

        //2)Reset txt
        ResetText_WS();

        //3)Move it
        PrepareAndMoveTextAndSave_WS(sWord);
    }
}
function OnWordEntered_WS() {
    if (_IsActivated) {
        //1)Prevent entering words
        jQuery("#" + _sIdTxt_WS).attr("readonly", "readonly");

        //2)Get txt entered
        var sWord = jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxt_WS).attr('value');

        //3)Reset txt
        ResetText_WS();

        //4)Move it
        PrepareAndMoveTextAndSave_WS(sWord);
    }
}
//**Tool**************************************************************************************
function CheckStringSpecialEntered_WS() {
    //1)Get txt entered
    var s = jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxt_WS).attr('value');

    //2)Check if special char entered 
    var sSpecial1 = ';';
    var sSpecial2 = ',';

    var iPosSpecial1 = s.lastIndexOf(sSpecial1, s.length - 1);
    var iPosSpecial2 = s.lastIndexOf(sSpecial2, s.length - 1);

    var bSecondSpecial3 = (s.split(/\s/g).length - 1) >= 3;

    if (iPosSpecial1 != -1 || iPosSpecial2 != -1 || bSecondSpecial3) {
        if (s.length > 1) {
            //Remove special char
            var sWord = s.substr(0, s.length - 1);

            //Send event
            OnStringSpecialEntered_WS(sWord);
        }
        else {
            //1)Reset field value
            ResetText_WS();

            //2)Show txt
            //CUSTOM HERE !
        }
    }
}
function CheckStringOnBlur_WS() {
    //1)Get txt entered
    var s = jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxt_WS).attr('value');

    //2)Send event
    if (s.length > 0)
        OnStringSpecialEntered_WS(s);


}
function ResetText_WS() {
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxt_WS).attr('value', '');
}
function PrepareAndMoveTextAndSave_WS(sWord) {
    //1)Reset word in label

    var sHtmlButtonRemover = "<div class='keyword_moving_delete' ><div>";
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).html('');
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).append("<div class='keyword_moving'><span>" + sWord + "</span> " + sHtmlButtonRemover + "</div>");

    //2)Show it
    var oPos = jQuery('#' + _sIdTxt_WS).position();
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).animate({ top: (oPos.top + 2) + 'px', left: (oPos.left + 2) + 'px' }, 0);
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).show();

    //3)Move it
    MoveText_WS(sWord);
}
function MoveText_WS(sWord) {
    //1)Prepare function
    var fn = function() {
        //Add new entry to container
        AddItemToEntryContainer_WS(sWord);

        //Reset css
        ResetCss_WS();

        //Allow entering words
        jQuery("#" + _sIdTxt_WS).removeAttr("readonly");

        jQuery("#" + _sIdTxt_WS).focus();
    };

    //2)Get next position in list
    var oPos = GetPosOfNextEntry_WS();

    //2)Move it
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).animate({ top: oPos.top + 'px', left: oPos.left + 'px' }, 500, fn);
}
function GetPosOfNextEntry_WS() {
    //Get pos of next entry
    var oPos = jQuery('#' + _sIdDivWordSelectedContainer_WS).position();
    var last = jQuery('#' + _sIdDivWordSelectedContainer_WS + " div:last").position();
    if (last) {
        last.left = last.left + jQuery('#' + _sIdDivWordSelectedContainer_WS + " div:last").width() + 5;
        oPos = last;
    }
    return oPos;
}
var _i = 0;
function AddItemToEntryContainer_WS(sWord) {
    //1)test if not exists
    var s = jQuery("#" + _idHdnValues).attr("value");
    if (sWord.trim().length > 0 && !s.startsWith(sWord + ',') && s.indexOf(',' + sWord + ',') < 0) {

        //2)Add element
        var sIdItemNew = "_divItem" + _i;
        var sHtmlButtonRemover = "<div onclick='javascript:RemoveItemToEntryContainer_WS(" + _i + ");return false;' class='keyword_item_delete' ></div>";
        jQuery('#' + _sIdDivWordSelectedContainer_WS).append("<div class='keyword_item' id='" + sIdItemNew + "'><span>" + sWord + "</span> " + sHtmlButtonRemover + "</div>");

        //3)Add to asp list
        document.getElementById(_idHdnValues).value = document.getElementById(_idHdnValues).value + sWord + ",";
        _i++;
    }
}
function RemoveItemToEntryContainer_WS(iItem) {
    var sIdItem = "_divItem" + iItem;

    var fn = function() {
        //Get wordlist and word
        var s = jQuery("#" + _idHdnValues).attr("value");
        var sVal = jQuery("#" + _sIdDivWordSelectedContainer_WS + " div[id=" + sIdItem + "] span").text();

        //Remove it
        var sNew = RemoveString_WS(s, sVal);
        jQuery("#" + _sIdDivWordSelectedContainer_WS + " div[id=" + sIdItem + "]").remove();
        document.getElementById(_idHdnValues).value = sNew;
    };

    //Effect
    jQuery("#" + _sIdDivWordSelectedContainer_WS + " div[id=" + sIdItem + "]").fadeTo(200, 0.01, fn);
}
function ResetCss_WS() {
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).hide();
    var oPos = jQuery('#' + _sIdTxt_WS).position();
    jQuery('#' + _sIdDivContainer_WS + ' #' + _sIdTxtMover_WS).animate({ top: oPos.top + 'px', left: oPos.left + 'px' }, 1);
}
function RemoveString_WS(s, sWord) {
    //Check for error
    if (s == null) alert("RemoveString_WS: Was null s");
    if (sWord == null) alert("RemoveString_WS: Was null sWord");

    var sArray = s.split(',');
    var sNew = '';
    for (i = 0; i < sArray.length; i++) {
        if (sArray[i].length > 0 && sArray[i] != sWord)
            sNew += sArray[i] + ','
    }

    return sNew
}
var _sInfoValEmpty = "You must enter at least one word !";
function CheckValues_WS() {
    //1)Get value
    var s = jQuery("#" + _idHdnValues).attr("value");

    //2)Verif
    if (s.length == 0) DisplayTxtInfo_WS(_sInfoValEmpty, true);
}
function DisplayTxtInfo_WS(sSentence, IsDisplayed) {
    if (IsDisplayed) {
        jQuery("#" + _sIdDivContainer_WS + " #" + _sIdLblInfo_WS).text(sSentence);
        jQuery("#" + _sIdDivContainer_WS + " #" + _sIdLblInfo_WS).show();
    }
    else jQuery("#" + _sIdDivContainer_WS + " #" + _sIdLblInfo_WS).hide();
}
///////////////////////////////////////////////////
