﻿var currentArea = '0';
function SwapAreaImage(imgID) {
    Cookie.dispose('area');
    Cookie.write('area', imgID);

    var areaID = imgID;
    selectedArea = areaID;
    imgID = 'img_Zone' + imgID;

    var currId = 'img_Zone' + currentArea;
    var currImg = $(currId).getProperty('src').replace("_current", "");
    $(currId).setProperty('src', currImg);   
    
    var imgProps = $(imgID).getProperty('src');
    if (imgProps.indexOf("current") == -1) {
        imgProps = imgProps.replace(".", "_current.");        
        currentArea = areaID;
        }
    else {
        imgProps = imgProps.replace("_current", "");
    }
    $(imgID).setProperty('src', imgProps);

    if (lastOpenCategory != '') {
        $(lastOpenCategory).setProperty('class', 'regButt');
    }
    if (lastOpenSubCategory != '' ) {
        $(lastOpenSubCategory).innerHTML = '';
    }
}

function ShowFastNavigation(div_FastNavTtile, div_FastNav) {
    $('div_FastNavTtile').setStyle('display', 'none');
    var divHeight = 170;
    $('div_FastNav').setStyles({ display: 'block', height: 0 });
    var myEffect = new Fx.Tween($('div_FastNav'), {
        property: 'height',
        duration: 800
    });
    myEffect.start(0, divHeight);
}

function HideFastNavigation() {
    var divNavHeight = 170;

    var myEffect = new Fx.Tween($('div_FastNav'), {
        property: 'height',
        duration: 800,
        onComplete: function() {
            $('div_FastNavTtile').setStyle('display', 'block');
            $('div_FastNav').setStyles({ display: 'none' })
        }
    });
    myEffect.start(divNavHeight, 0);
}

function SetAreaCookie(areaID) {
    Cookie.dispose('area');
    Cookie.write('area', areaID);
}


var lastOpenCategory = '';
var lastOpenSubCategory = '';

function ShowHideSubMenu(categoryID, divMainCategory, divSubMenu) {
    var fade = $(divSubMenu);
    var mainCss = $(divMainCategory).getProperty('class');
    if (mainCss.indexOf('opened') == -1)
    {
        var url = "/ajax/MainCategoryHD.aspx?catid=" + categoryID + "&area=" + selectedArea + "&t=2";

        var req = new Request.HTML({
            method: 'get',
            url: url,
            data: { 'do': '1' },           
            update: fade,
            onComplete: function() {                            
                if (lastOpenCategory != '') {
                    $(lastOpenCategory).setProperty('class', 'regButt');
                }
                if (lastOpenSubCategory != '' && lastOpenSubCategory != divSubMenu) {
                    $(lastOpenSubCategory).innerHTML = '';
                }
                $(divMainCategory).setProperty('class', 'regButt opened');
                $(divSubMenu).setProperty('class', 'boxType2 subMenu');
                lastOpenCategory = divMainCategory;
                lastOpenSubCategory = divSubMenu;
            }
        }).send();        
    }
    else {
         fade.innerHTML = '';
        $(divMainCategory).setProperty('class', 'regButt');      
    }
}




function OpenPageName(URL, w, h, t, l, n) {
    window.open(URL, n, 'scrollbars=1,width=' + w + ',height=' + h + ', top=' + t + ', left=' + l + '');
}
function OpenPage(URL, w, h, t, l) {
    window.open(URL, 'openWindow', 'scrollbars=1,width=' + w + ',height=' + h + ', top=' + t + ', left=' + l + '');
}


function OpenDeal(url) {
    var newPopUp = window.open(url, 'Deal', 'scrollbars=1, width=670, height=800, top=50, left=300');    
}

function OpenNews(url) {
    var newPopUp = window.open(url, 'Deal', 'scrollbars=1, width=650, height=650, top=50, left=300');
}


function floatw(SuppId) {
    newWin1 = window.open("http://www.mitchatnim.co.il/SupplierDetails.asp?id=" + SuppId + "&Cat=9", "popup1", "width=543,height=500, status=no,scrollbars=yes,top=20")
}


function CleanTheCharacters() {
    var flag = "0";
    var theWord; var tempVal; var i; theWord = document.getElementById('keyword').value; tempVal = document.getElementById('keyword').value.length;
    for (i = 0; i < tempVal; i++) {
        //(theWord.charAt(i) == "-") ||
        if ((theWord.charAt(i) == "<") || (theWord.charAt(i) == ">") || (theWord.charAt(i) == "%") || (theWord.charAt(i) == "@") || (theWord.charAt(i) == "*") || (theWord.charAt(i) == "'") || (theWord.charAt(i) == "&") || (theWord.charAt(i) == "$") || (theWord.charAt(i) == "#") || (theWord.charAt(i) == "%")) {
            document.getElementById('keyword').value = "";
            flag = "1";
        }
    }

    if (flag == "0") {
        return true;
    }
    else {
        alert("החיפוש שהוקלד מכיל תגים לא חוקיים");
        return false;
    }
}


function CleanTheCharactersIndexOf() {
    var flag = "0";
    var theWord; var tempVal; var i; theWord = document.getElementById('keyword').value.toLowerCase(); tempVal = document.getElementById('keyword').value.length;
    if ((theWord.indexOf('<sc') != -1) || (theWord.indexOf('delete') != -1) || (theWord.indexOf('update') != -1) || (theWord.indexOf('select') != -1) || (theWord.indexOf('insert') != -1) || (theWord.indexOf('alert') != -1) || (theWord.indexOf('drop') != -1) || (theWord.indexOf('table') != -1)) {
        alert("החיפוש שהוקלד מכיל תגים לא חוקיים");
        document.getElementById('keyword').value = "";
        return false;
    }
    return true;
}



function ShowHide(layer_ref) {
    var dis = 'none';
    if ($(layer_ref).style.display == 'block') {
        dis = 'none';
    }
    else {
        dis = 'block';
    }

    $(layer_ref).style.display = dis;
}


function Show(divID) {
    $(divID).style.display = 'block';
}

function OpenCatalog(Link) {
    open(Link, 'catalog', 'toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=yes,copyhistory=no,scrollbars=no,width=1020,height=700,top=0,left=0');
}

function OpenVideo(link, title) {    
    open("openVideo.aspx?" + link + "&title=" + title + ",'video','width=446,height=358,toolbar=0,resizable=0')");
}

function fbs_click(site, TitleDiv) {
    if (site == 'facebook') {
        u = location.href;
        t = document.getElementById(TitleDiv); //the article headline
        if (t == null || t == 'undefined')
            t = TitleDiv;
        else t = t.innerText;
        window.open("http://www.facebook.com/sharer.php?u=" + encodeURIComponent(u) + "&t=" + encodeURIComponent(t), "sharer", "toolbar=0, status=0, width=626, height=436,scrollbars=1");
    }
    else {
        u = location.href;
        window.open("http://twitter.com/home?status=" + encodeURIComponent(u + " כרגע קורא/ת "), "sharer", "toolbar=0, status=0, width=768, height=436,scrollbars=1");
    }
    return false;
}




function ClearContactForm() {

    $(txtBusinessName).value = '';
    $(ddlclassification).value = "0";
    $(txtSivugAher).value = '';
    $(txtAddress).value = '';
    $(txtCity).value = '';
    $(txtFName).value = '';
    $(txtLName).value = '';
    $(txtPhone1).value = '';
    $(txtPhone2).value = '';
    $(txtMobile).value = '';
    $(txtFax).value = '';
    $(txtEmail).value = '';
    $(txtNote).value = '';    
}

function InsertContact() {

    if ($(txtBusinessName).value == '') {
        alert("הכנס שם העסק");
        $(txtBusinessName).focus();
        return false;
    }
    if ($(ddlclassification).value == "0" && $(txtSivugAher).value == "") {
        alert("בחר סיווג");
        $(ddlclassification).focus();
        return false;
    }
    if ($(txtCity).value == '') {
        alert("הכנס עיר או ישוב");
        $(txtCity).focus();
        return false;
    }
    if ($(txtFName).value == '') {
        alert("הכנס שם פרטי");
        $(txtFName).focus();
        return false;
    }
    if ($(txtLName).value == '') {
        alert("הכנס שם משפחה");
        $(txtLName).focus();
        return false;
    }
    
    if ($(txtPhone1).value == '') {
        alert("הכנס טלפון");
        $(txtPhone1).focus();
        return false;
    }
    if (isNaN($(txtPhone1).value)) {
        alert("טלפון לא חוקי");
        $(txtPhone1).focus();
        return false;
    }
    if ($(txtPhone2).value != "") {
        if (isNaN($(txtPhone2).value)) {
            alert("טלפון 2 לא חוקי");
            $(txtPhone2).focus();
            return false;
        }
    }
    if ($(txtMobile).value == '') {
        alert("הכנס טלפון סלולרי");
        $(txtMobile).focus();
        return false;
    }
    if (isNaN($(txtMobile).value)) {
        alert("נייד לא חוקי");
        $(txtMobile).focus();
        return false;
    }
    if ($(txtFax).value != "") {
        if (isNaN($(txtFax).value)) {
            alert("פקס 2 לא חוקי");
            $(txtFax).focus();
            return false;
        }
    }
   
    if ($(txtEmail).value != "") {
        if (isokEmail($(txtEmail).value) == false) {
            alert("אימייל לא חוקי");
            $(txtEmail).focus();
            return false;
        }
    }

    return true;
}

function isokEmail(string) {
    if (string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true;
    else
        return false;
}



//------------------------------//
//          Opinion             //
//------------------------------//


function ShowOpinionDiv() {

    pageTracker._trackEvent('Feedback', window.location);

    PresentDialogDiv('divShadeWindow', 'divOpinion');

    $('divOpinion').setStyle('display', 'block');
    var req = new Request.HTML({
        method: 'get',
        url: "/ajax/AddOpinion.aspx?pageUrl=" + escape(window.location),
        update: $('divOpinion'),
        onRequest: function() { $('divOpinion').empty().innerHTML = '<div style="padding-top:20px"><center><img src="/images/ajax-loaderForum.gif" ></center></div>'; }
    }).send();
}

function CloseOpinionDiv() {
    $('divOpinion').setStyle('display', 'none');
    $('divOpinion').empty().innerHTML = '';
    $('divShadeWindow').setStyle('display', 'none');
}

function ReplaceTopic(TopicId, DivTopicId) {

    //Replace Tab Topic CSS
    $(DivTopicId).removeClass("tabUnSelected");
    $(DivTopicId).addClass("tabSelected");
    $(SelectedTopicDiv).removeClass("tabSelected");
    $(SelectedTopicDiv).addClass("tabUnSelected");

    //Replace SubTopic DDL
    $("div_SubTopic_" + SelectedTopicId).setStyle('display', 'none');   //Close Open Div
    $("div_SubTopic_" + TopicId).setStyle('display', 'block');          //Open New Div

    //Update Selected Fields
    SelectedTopicDiv = DivTopicId;                              //Update Selected Topic Div
    SelectedTopicId = TopicId;                                  //Update Selected Topic Id
    SelectedSubTopicId = $(TopicId + "_SelectedValue").value;   //Update Selected Sub Topic Id
}

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}

var regEmail = /^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$/;

function InsertOpinion() {

    if ($('txtName').value == '') {
        $('txtErrorMessage').innerHTML = "* חובה להזין שם";
        $('txtName').focus();
        return false;
    }
    else if ($('txtDescription').value == '') {
        $('txtErrorMessage').innerHTML = "* חובה להזין תיאור";
        $('txtDescription').focus();
        return false;
    }
    else if ($('txtEmail').value != "" && !regEmail.test($('txtEmail').value)) {
        $('txtErrorMessage').innerHTML = "* חובה להזין כתובת דוא\"ל תקינה";
        $('txtEmail').focus();
        return false;
    }
    else {

        $('txtErrorMessage').innerHTML = '';

        var Grade = $('SelectedGradeValue').value;

        var req = new Request.HTML({
            url: '/ajax/InsertOpinion.aspx?topicId=' + SelectedTopicId + '&subTopicId=' + SelectedSubTopicId + '&grade=' + Grade + '&pageUrl=' + escape(PageUrl),
            update: $('divOpinion')
        }).post($('frm_AddOpinion'));
    }
}

function ShowHideGradePopupDiv(divID) {
    if ($(divID).getStyle('display') == 'none') {
        $(divID).setStyle('display', 'block');
    }
    else {
        $(divID).setStyle('display', 'none');
    }
}

function DropDownGradeSelected(NewValue) {
    $('txtGradeTitle').innerHTML = NewValue;        //Update Text
    $('SelectedGradeValue').value = NewValue;       //Update Value
}


//--------------------//
//  Shade Div         //
//--------------------//

var IEmax = 2000;
var IE = (navigator.userAgent.indexOf('MSIE') != -1) ? true : false;
var xDialogBoxPosition = 0;
var yDialogBoxPosition = 0;
var ViewportHeight = 0;
var RealLength = 0;
var PageWidth = 0;
var PageHeight = 0;
var ShadowDiv;
var DialogDiv;

function GetViewportDimensions() {
    var viewX = 0;
    var viewY = 0;
    if (self.innerWidth) {
        viewX = self.innerWidth;
        viewY = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth) {
        viewX = document.documentElement.clientWidth;
        viewY = document.documentElement.clientHeight;
    }
    else if (document.body) {
        viewX = document.body.clientWidth;
        viewY = document.body.clientHeight;
    }
    return Array(viewX, viewY);
}

function GetPageDimensions() {
    var pageX = 0;
    var pageY = 0;
    if (window.innerHeight && window.scrollMaxY) {
        pageX = window.innerWidth + window.scrollMaxX;
        pageY = window.innerHeight + window.scrollMaxY;
    }
    else if (document.body.scrollHeight > document.body.offsetHeight) {
        pageX = document.body.scrollWidth;
        pageY = document.body.scrollHeight;
    }
    else if (document.body.scrollWidth && document.body.scrollHeight) {
        pageX = document.body.scrollWidth;
        pageY = document.body.scrollHeight;
    }
    else {
        pageX = document.body.offsetWidth;
        pageY = document.body.offsetHeight;
    }
    var viewDimensions = GetViewportDimensions();
    if (pageX < viewDimensions[0]) { pageX = viewDimensions[0]; }
    if (pageY < viewDimensions[1]) { pageY = viewDimensions[1]; }
    else if (IE) {
        pageY += 25;
        RealLength = pageY;
        ViewportHeight = viewDimensions[1];
        if (pageY > IEmax) { pageY = IEmax; }
    }
    return Array(pageX, pageY);
}

function ShadeTheWindow(shadow) {
    var pageDimensions = GetPageDimensions();
    PageWidth = pageDimensions[0];
    PageHeight = pageDimensions[1];
    ShadowDiv = document.getElementById(shadow);
    ShadowDiv.style.width = PageWidth + "px";
    ShadowDiv.style.height = PageHeight + "px";
    ShadowDiv.style.display = "block";
}

function PositionDialogDiv() {
    var xScrollPosition = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
    var yScrollPosition = window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
    if (IE && PageHeight == IEmax) {
        var shadowpos = (yScrollPosition < (IEmax - ViewportHeight)) ? 0 : yScrollPosition - 1;
        if ((shadowpos + PageHeight) > RealLength) { shadowpos = RealLength - IEmax; }
        ShadowDiv.style.top = shadowpos + "px";
    }
    var dArr = GetViewportDimensions();
    remWidth = parseInt(DialogDiv.style.width.replace("px", ""));
    if (DialogDiv.style.height != "")
        remHeight = parseInt(DialogDiv.style.height.replace("px", ""));
    else
        remHeight = 100;

//    var divOpinionWidth = $('divOpinion').getStyle('width').toInt();
//    var divOpinionHeight = $('divOpinion').getStyle('height').toInt();

//    DialogDiv.style.left = (dArr[0] - divOpinionWidth) / 2 + xScrollPosition + "px";
//    DialogDiv.style.top = (dArr[1] - divOpinionHeight) / 2 + yScrollPosition + "px";

    var DialogDivWidth = $(DialogDiv).getStyle('width').toInt();
    var DialogDivHeight = $(DialogDiv).getStyle('height').toInt();
    DialogDiv.style.left = (dArr[0] - DialogDivWidth) / 2 + xScrollPosition + "px";
    DialogDiv.style.top = (dArr[1] - DialogDivHeight) / 2 + yScrollPosition + "px";
    
}

function DisplayDialogDiv(dialog) {
    DialogDiv = document.getElementById(dialog);
    if (xDialogBoxPosition == 0 && yDialogBoxPosition == 0) {
        xDialogBoxPosition = parseInt(DialogDiv.style.left);
        yDialogBoxPosition = parseInt(DialogDiv.style.top);
    }
    PositionDialogDiv();
    DialogDiv.style.display = "block";
    window.onscroll = PositionDialogDiv;
}

function PresentDialogDiv(shadow, dialog) {
    ShadeTheWindow(shadow);
    DisplayDialogDiv(dialog);
}

function RemoveDialogDiv() {
    DialogDiv.style.display = "none";
    ShadowDiv.style.display = "none";
}

//----------------------------------------------------------------------------
//  Facebook
//----------------------------------------------------------------------------

function CloseFaceBookBar() {
    var bar = $('div_FacebookBar');
    var myFx = new Fx.Slide(bar).slideOut();

}

function hidefacebookbar() {
    var bar = $('div_FacebookBar');
    var myFx = new Fx.Slide(bar).hide();
}

function OpenFaceBookBar() {
    var bar = $('div_FacebookBar');
    var myFx = new Fx.Slide(bar).slideIn();
}


function FacebookLogin(type) {

    FB.login(function(response) {
        if (response.session) {
            if (response.perms) {
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions

                var req = new Request.HTML({
                    method: 'get',
                    url: '/ajax/UpdateUserFacebook.ashx'
                }).send();

                switch (type) {
                    case "ConnectBar":
                        CloseFaceBookBar();
                        break;
                    case "Forum":
                        window.location.reload();
                        break;
                }

            } else {
                // user is logged in, but did not grant any permissions
            }
        } else {
            // user is not logged in
        }
    }, { perms: 'publish_stream' });

}

//----------------------------------------------------------------------------
//  AutoCompleteSuppliers
//----------------------------------------------------------------------------

var numOfSuppliersAC = 0;
var selectedSupplierAC = -1;
function AutoCompleteSuppliers(type, control, container, e, itemID) {
    if (e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13) {
        numOfSuppliersAC = 0;
        selectedSupplierAC = -1;

        if (itemID == null) {
            itemID = "";
        }
        
        var url = "/ajax/AutoCompleteSuppliers.ashx?keyword=" + escape($(control).value) + "&type=" + type + "&itemID=" + itemID;
        var req = new Request.HTML({
            method: 'get',
            url: url,
            update: $(container),
            onComplete: function(response) {
                numOfSuppliersAC = parseInt(response.length) - 1;
                if (response.length >= 1 && e.keyCode != 13) {
                    $(container).setStyle("display", "block");
                } else {
                    $(container).setStyle("display", "none");
                }
            }
        }).send();
    } else {
        var arrChildren = new Array();
        arrChildren = $(container).getChildren();
        var prev = 0;
        var current = 0;
        if (e.keyCode == 40) {
            prev = selectedSupplierAC != -1 ? selectedSupplierAC : 0;
            selectedSupplierAC++;
            selectedSupplierAC = selectedSupplierAC > numOfSuppliersAC ? 0 : selectedSupplierAC;
            arrChildren[prev].setStyle("background-color", "#FDFFFF");
            arrChildren[selectedSupplierAC].setStyle("background-color", "#E5E5E5");

        } else if (e.keyCode == 38) {
            current = selectedSupplierAC != numOfSuppliersAC ? selectedSupplierAC : numOfSuppliersAC;
            selectedSupplierAC--;
            selectedSupplierAC = selectedSupplierAC < 0 ? numOfSuppliersAC : selectedSupplierAC;
            arrChildren[current].setStyle("background-color", "#FDFFFF");
            arrChildren[selectedSupplierAC].setStyle("background-color", "#E5E5E5");
        }        
    }
}

function disableEnterKey(ev) {

    var isIE = false;
    if (navigator.appName.indexOf("Microsoft") > -1 || navigator.appName.indexOf("IE") > -1) {
        isIE = true;
    }
    if ((isIE && event.keyCode == 13) || (!isIE && ev.which == 13)) {
        if (isIE) {
            event.cancelBubble = true;
            event.returnValue = false;
        } else {
            ev.preventDefault();
            ev.stopPropagation();
        }
        return;
    }
}


//----------------------------------------------------------------------------



function Mit_SSO_CallBack(parameters) {
    var ssoJSON = JSON.decode(parameters);

    Cookie.set('sso', ssoJSON.Token);

    $('divSSOLogout').setStyle('display', 'block');
    $('imgLogin').setAttribute('src', '/images/butt_join_share2.gif');

    $('imgSSOImage').setProperty('src', ssoJSON.PreferableImage);
    $('spnSSOName').innerHTML = ssoJSON.PreferableName;
}

function UserLogout(page) {
    Cookie.remove('sso');
    document.location = 'http://sso.zap.co.il/Account/Logout.aspx?siteid=19&returnurl=' + page;
}
