﻿
////////////////////////////////////
// Global vars:
var CitiesArr = new Array();
var BusinessesArr = new Array();
var DegreesArr = new Array();
var PhonePrefixArr = new Array();

PhonePrefixArr = "050,052,054,055,057,058,072,074,077,02,03,04,08,09".split(',');

////////////////////////////////////////////////////////////
// Prototypes and global functions

function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.Append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.Clear = function() {
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.ToString = function() {
    return this.strings.join("");
}


String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}


String.prototype.GetFromCode = function() {

    var TmpArr = this.split('.');
    var Result = '';
    for (var i = 0; i < TmpArr.length; i++) {

        Result += String.fromCharCode(parseInt(TmpArr[i]));
    }
    return (Result);
}

String.prototype.isValidMail = function() {
    var _email = this;
    var emailReg = /^[a-z][a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i
    return emailReg.test(_email);
}


String.prototype.isValidIdNum = function() {
    var iIDLength = this.length,
        i,
        iID = this;
    if (iIDLength < 9) {
        for (i = 0; i < 9 - iIDLength; i++) {
            iID = "0" + iID;
        }
        iIDLength = 9;
    }

    var iCount = 0,
        iCurrent,
        iTemp;

    for (i = 2; i < iIDLength + 2; i++) {
        iTemp = iID.substr(i - 2, 1) * 1;
        if (iTemp != 0) {
            iCurrent = ((i % 2) + 1) * iTemp;
            iCount += iCurrent > 9 ? 1 + iCurrent % 10 : iCurrent;
        }
    }
    return (iCount % 10 === 0)
}



function StringBuilder(value) {
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function() {
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function() {
    return this.strings.join("");
}

String.prototype.ReplaceAll = function(s1, s2) {

    if (this.indexOf(s1) > -1) {
        return this.split(s1).join(s2);
    }
    else {
        return this;
    }
}


String.prototype.CutAfterLimit = function(limit) {
    if (this.length <= limit) {
        return (this);
    }

    var i = 0;
    var currIndex = limit;
    while (this[currIndex] != ' ' && currIndex > 0) {
        currIndex--;
    }
    if (currIndex == 0) {
        currIndex = limit;
    }
    return (this.substring(0, currIndex) + "..");
}


String.prototype.isValidPhone = function() {

    phoneNumber = this.trim();
    if (phoneNumber.length != 7) {
        return (false);
    }

    var strArr = phoneNumber.split("");
    var i = 0;
    var j = 0;
    if (strArr[0] == '0' || strArr[0] == '1') {
        return (false);
    }

    var change = 0;
    for (i = 0; i < strArr.length; i++) {
        for (j = 0; j < strArr.length; j++) {
            if (strArr[i] != strArr[j]) {

                change = 1;
                break;
            }
        }
    }

    if (change == 0) 
    {
        return (false);
    }

    return (true);
}


////////////////////////////////////////////////////////////
// Function returns HTTP request object for all browsers.
function getHttpRequestObj() {
    var xmlhttp;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}


function LogUserOut() 
{
    var RetToPage = window.location.href;
    window.location.href = '/Logout';
}

////////////////////////////////////////////////////////////
// Function returns get parameter value from url string
function GetUrlParam(ParamName, UrlStr) 
{
    var reParam = new RegExp('(?:[\?&]|&)' + ParamName + '=([^&]+)', 'i');
    var match = UrlStr.match(reParam);
    return (match && match.length > 1) ? match[1] : '';
}

/////////////////////////////////////////////////////////////////////
// Auto Complete Parsing Functions:
// this function will parse xml and return as a array of string
function parseXML(xml) {
    var results = [];

    $(xml).find('item').each(function() {

        var text = $.trim($(this).find('text').text());
        var value = $.trim($(this).find('value').text());
        var extra = $.trim($(this).find('extra').text());
        var category = $.trim($(this).find('category').text());
        var icon = $.trim($(this).find('icon').text());

        results[results.length] = { 'data': { text: text, value: value, extra: extra, category: category, icon: icon },
        'result': text, 'value': value, 'extra': extra, 'category': category, 'icon': icon
        };
    });
    return results;
};

function formatItem(data) {
    return data.text;
};

function formatResult(data) {
    return data.text;
};


///////////////////////////////////////////////////////////
// Function returns only numbers when typing in textbox
function numbersonly(e, decimal) 
{
    var key;
    var keychar;

    if (window.event) {
        key = window.event.keyCode;
    }
    else if (e) {
        key = e.which;
    }
    else {
        return true;
    }
    keychar = String.fromCharCode(key);

    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
        return true;
    }
    else if ((("0123456789").indexOf(keychar) > -1)) {
        return true;
    }
    else if (decimal && (keychar == ".")) {
        return true;
    }
    else
        return false;
}



//////////////////////////////////////////////////////////////////////
// Cookie Functions
function createCookie(name, value, days, ipath) {
    if (ipath == undefined) {
        ipath = "";
    }
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/" + ipath;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

//////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////////
// Function returns array of businesses - seperated by | for the auto complete
// AJAX Page: /ajax/GetBusinessesForAutoComplete.aspx
function GetBusinessesForAutoComplete(TextBoxObjId) {

    if (BusinessesArr.length > 0) {
        $("#" + TextBoxObjId).autocomplete
            (
            BusinessesArr,
            {
                matchContains: true
            }
            );
        return;
    }

    var pageURL = "/ajax/GetBusinessesForAutoComplete.aspx";
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            BusinessesArr = xObj.responseText.split('|');
            $("#" + TextBoxObjId).autocomplete
            (
            BusinessesArr,
            {
                matchContains: true
            }

            );
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);
}
/////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////
// Function returns array of businesses - seperated by | for the auto complete 
// With their address and city
// AJAX Page: /ajax/GetBusinessesForAutoCompleteWithLocation.aspx
function GetBusinessesForAutoCompleteWithLocation(TextBoxObjId) {

    if (BusinessesArr.length > 0) {
        $("#" + TextBoxObjId).autocomplete
            (
            BusinessesArr,
            {
                matchContains: true
            }
            );
        return;
    }

    var pageURL = "/ajax/GetBusinessesForAutoCompleteWithLocation.aspx";
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            BusinessesArr = xObj.responseText.split('|');
            $("#" + TextBoxObjId).autocomplete
            (
            BusinessesArr,
            {
                matchContains: true
            }

            );
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);
}
/////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
// Function returns array of Degrees - seperated by | for the auto complete
// AJAX Page: /ajax/GetDegreesForAutoComplete.aspx
function GetDegreesForAutoComplete(TextBoxObjId) {

    if (DegreesArr.length > 0) {
        $("#" + TextBoxObjId).autocomplete
            (
            DegreesArr,
            {
                matchContains: true
            }
            );
        return;
    }

    var pageURL = "/ajax/GetDegreesForAutoComplete.aspx";
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            DegreesArr = xObj.responseText.split('|');
            $("#" + TextBoxObjId).autocomplete
            (
            DegreesArr,
            {
                matchContains: true
            }

            );
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);
}
/////////////////////////////////////////////////////////////////////////







////////////////////////////////////////////////////////////////////
// Auto Complete:
// Functions for getting autocomplete ajax values

function TopAutoComplete(InputObjId) 
{


    // get the input field
    var input = $('#' + InputObjId);
    // This function opens the full list before even typing
    // if you dont want this  omit this part.
    input.one('click', function() {
        $(this).focus().click().select();
        $(this).one('click', arguments.callee);
    });
    // Jquery autocomplete with xml file
    input.autocomplete
           (
                '/ajax/TopAutoComplete.aspx',
                {
                    delay: 10,
                    matchSubset: 1,
                    matchContains: 1,
                    minChars: 4,
                    parse: parseXML,
                    formatItem: formatItem,
                    max:30,
                    formatResult: formatResult
                }).result(function(event, item) 
                {
                    var GoToUrl = item.extra;
                    location.href = GoToUrl;
                }
            );
}


function InstitusionsAutoComplete(InputObjId) 
{
    // get the input field
    var input = $('#' + InputObjId);
    // This function opens the full list before even typing
    // if you dont want this  omit this part.
    input.one('click', function() {
        $(this).focus().click().select();
        $(this).one('click', arguments.callee);
    });
    // Jquery autocomplete with xml file
    input.autocomplete
           (
                '/ajax/InstitutionsAutoComplete.aspx',
                {
                    delay: 10,
                    matchSubset: 1,
                    matchContains: 1,
                    minChars: 2,
                    parse: parseXML,
                    formatItem: formatItem,
                    formatResult: formatResult
                }).result(function(event, item) 
                {
                    var GoToUrl = item.extra;
                    location.href = GoToUrl;
                }
            );

}



function CitiesAutoComplete(InputObjId) 
{
    // get the input field
    var input = $('#' + InputObjId);
    // This function opens the full list before even typing
    // if you dont want this  omit this part.
    input.one('click', function() {
        $(this).focus().click().select();
        $(this).one('click', arguments.callee);
    });
    // Jquery autocomplete with xml file
    input.autocomplete
           (
                '/ajax/CitiesAutoComplete.aspx',
                {
                    delay: 10,
                    matchSubset: 1,
                    matchContains: 1,
                    minChars: 2,
                    parse: parseXML,
                    formatItem: formatItem,
                    formatResult: formatResult
                }).result(function(event, item) 
                {
                    
                }
            );

}


/////////////////////////////////////
// Search Institution

function SearchInstitution(SearchKey) 
{

    SearchKey = SearchKey.trim();
    window.location.href = "/AllSchools.aspx?Keyword=" + encodeURI(SearchKey);
    
}



/*
SendSiteContact() - 
Function for sending user contact
*/
function SendSiteContact() 
{
    var err = 0;
    var ContactName = document.getElementById("ContactNameTxT");
    var ContactEmail = document.getElementById("ContactEmailTxT");
    var ContactPhone = document.getElementById("ContactPhoneTxT");
    var ContactMessage = document.getElementById("ContactMessageTxT");
    var ContactSubject = document.getElementById("ContactSubjectTxT");

    if (ContactName.value.trim() == '' || ContactName.value.trim() == 'יש להזין שם מלא') 
    {
        ContactName.value = 'יש להזין שם מלא';
        err = 1;
    }

    if (!ContactEmail.value.isValidMail()) 
    {
        ContactEmail.value = 'יש להזין כתובת אימייל תקנית';
        err = 1;
    }

    if (ContactSubject.value.trim() == '' || ContactSubject.value.trim() == 'יש להזין את נושא הפניה') {
        ContactSubject.value = 'יש להזין את נושא הפניה';
        err = 1;
    }

    if (ContactMessage.value.trim() == '' || ContactMessage.value.trim() == 'יש להזין את פרטי הפניה') 
    {
        ContactMessage.value = 'יש להזין את פרטי הפניה';
        err = 1;
    }

    if (err) 
    {
        return;
    }

    var pageURL = "/ajax/SendContact.aspx";
    var params = "ContactName=" + encodeURIComponent(ContactName.value) + "&ContactEmail=" + encodeURIComponent(ContactEmail.value) + "&ContactMessage=" + encodeURIComponent(ContactMessage.value) + "&ContactPhone=" + encodeURIComponent(ContactPhone.value) + "&ContactSubject=" + encodeURIComponent(ContactSubject.value);

    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
    if (xObj.readyState == 4) 
        {
            document.getElementById("ContactTable").style.display = 'none';
            document.getElementById("ContactSent").style.display = '';
        }
    };


    xObj.open("POST", pageURL, true);
    xObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xObj.send(params);
}


function ClickOnContactField(FieldObj) 
{
    var str = FieldObj.value.trim();
    if (str == "יש להזין שם מלא" || str == "יש להזין כתובת אימייל תקנית" || str == "יש להזין את נושא הפניה" || str == "יש להזין את פרטי הפניה") 
    {
        FieldObj.value = '';
    }

}



function ShowSmallHelp(CodeName, WriteToObjectId) 
{
    var WriteToObject = document.getElementById(WriteToObjectId);
    var pageURL = "/ajax/GetContentText.aspx?CodeName=" + encodeURI(CodeName);
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            var ContentText = xObj.responseText;
            var HtmStr = "<div onclick=\"document.getElementById('" + WriteToObjectId + "').innerHTML=''\" class=\"HelpDiv\">";
            HtmStr += "<img class=\"Close\" onclick=\"document.getElementById('" + WriteToObjectId + "').innerHTML=''\" title=\"סגור\" src=\"/images/SmallQmarkClose.jpg\" />"; 
            HtmStr += ContentText;
            HtmStr += "</div>";
            WriteToObject.innerHTML = HtmStr;
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);    

}




//////////////////////////////////////////////////////////////////////////
// Function returns Related Degrees XML
// AJAX Page: /ajax/GetRelatedDegrees.aspx
function GetRelatedDegrees(DegreeId) 
{
    var PageURL = "/ajax/GetRelatedDegrees.aspx?DegreeId=" + DegreeId;
    var HtmStr = '';
    $.ajax
    (
        {
            url: PageURL,
            global: false,
            type: "GET",
            dataType: "xml",
            async: false,
            success:
                    function(xml) 
                    {
                        $(xml).find("Degree").each(function() 
                        {
                            HtmStr = GetRelatedDegreesHtml(xml);
                        });
                    }
        }
    )

    return(HtmStr);
}


function GetRelatedDegreesHtml(xml) 
{
    var HtmStr = '';
    var NumOfDegrees = 0;
    $(xml).find("Degree").each(function() 
    {
        var DegreeId = $(this).find('DegreeId').text();
        var DegreeName = $(this).find('DegreeName').text();
        var InstitutionId = $(this).find('InstitutionId').text();
        var InstitutionName = $(this).find('InstitutionName').text();
        var DegreeTypeName = $(this).find('DegreeTypeName').text();
        var Logo = $(this).find('Logo').text();
        var NumOfReviews = $(this).find('NumOfReviews').text();
        HtmStr += '<div class="RelatedDegree">';
        HtmStr += '<input type="checkbox" class="RelatedDegreeChk" value="' + DegreeId + '" name="'+ InstitutionId + '" /> ';
        HtmStr += '<img class="Logo" src="/uploads/' + Logo + '" /> ';
        HtmStr += '<div class="Text">' + DegreeName + ' ' + DegreeTypeName + ', ' + InstitutionName + '</div>';
        HtmStr += '</div>';
        HtmStr += '<div class="ClearFix"></div>';
        NumOfDegrees++;
    });
    return(HtmStr);
}





/*
GetDegreeSpecialties() - 

*/
function GetDegreeSpecialties(DegreeId) 
{

    var DegreePageURL = "/ajax/GetDegree.aspx?DegreeId=" + DegreeId;
    var HtmStr = '';
    $.ajax
    (
        {
            url: DegreePageURL,
            global: false,
            type: "GET",
            dataType: "xml",
            async: false,
            success:
                    function(xml) {
                        var Specialties = $(xml).find("Specialties").text();
                        HtmStr = Specialties;

                    }
        }
    )

    return (HtmStr);

}




/////////////////////////////////////////////////////////////////////////
// Function save analitycs lead statistic by executing /LeadSentFrame.aspx
// By writing it to LeadSentDiv (Located in the master page)
function WriteFrameStat(FormLocation, ActionType, SourceLocation) 
{

    if (SourceLocation == undefined) 
    {
        SourceLocation = '';
    }
    if (FormLocation == '' || FormLocation == undefined) 
    {
        if (Force_LeadLocation != '' && FormLocation != undefined) 
        {
            FormLocation = Force_LeadLocation;
        }
    }
    var IframeUrl = "/StatsFrame.aspx?FormLocation=" + encodeURI(FormLocation) + "&ActionType=" + encodeURI(ActionType) + "&SourceLocation=" + encodeURI(SourceLocation);
    var IframeObj = document.getElementById("LeadSentDiv");
    if (!IframeObj) {
        IframeObj = window.parent.document.getElementById("LeadSentDiv");
    }

    IframeObj.innerHTML = "<iframe style=\"width:0;\" src=\"" + IframeUrl + "\" /></iframe>";
}




function SaveUserFollowing(DegreeId, InstitutionId) 
{

    var pageURL = "/ajax/SaveUserFollowing.aspx?DegreeId=" + DegreeId + "&InstitutionId=" + InstitutionId;
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            window.location.href = window.location.href;
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);

}


function RemoveUserFollowing(DegreeId, InstitutionId) 
{
    var pageURL = "/ajax/RemoveUserFollowing.aspx?DegreeId=" + DegreeId + "&InstitutionId=" + InstitutionId;
    var xObj = getHttpRequestObj();
    xObj.onreadystatechange = function() {
        if (xObj.readyState == 4) {
            window.location.href = window.location.href;
        }
    }
    xObj.open("get", pageURL, true);
    xObj.send(null);
}

/////////////////////////////////////
// Cookies

function CreateCookie(name, value, days, ipath) {
    if (ipath == undefined) 
    {
        ipath = "";
    }
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/" + ipath;
}

function ReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function EraseCookie(name) {
    CreateCookie(name, "", -1);
}



function getRealLeft(Obj) 
{
    var L = 0;
    var tempEl = Obj;
    while (tempEl.parentNode) {
        L += (tempEl.offsetLeft) ? tempEl.offsetLeft : 0;
        if (tempEl == document.body) break;
        tempEl = tempEl.parentNode;
    }
    return L;
}



