﻿String.prototype.format = function() {
    if (arguments.length < 1) {
        return undefined;
    } else {
        var t = arguments[0];
        for (var i = 1; i < arguments.length; i++) {
            var reg = new RegExp("\\{" + (i - 1) + "\\}", "gi");
            t = t.replace(reg, arguments[i]);
        }
        return t;
    }
}

function _get(obj) 
{
    return (typeof obj == 'object' ? obj : document.getElementById(obj));
}

function _set(obj, value) {
    obj = _get(obj);

    if (obj) {
        if (obj.value || obj.value == '') {
            obj.value = value;
        } else if (obj.innerHTML || obj.innerHTML == '') {
            obj.innerHTML = value;
        }
    }
}


function _remove(obj) {
    obj = _get(obj);

    if (obj) {
        obj.parentNode.removeChild(obj);
    }
}
function _show(obj) {
    obj = _get(obj);

    if (obj) {
        if (obj.style.visibility == 'hidden') 
        {
            obj.style.visibility == 'visible';
        }
        else 
        {
            obj.style.display = '';
        }
    }
}

function _hide(obj) {
    obj = _get(obj);

    if (obj) {
        if (obj.style.visibility == 'visible')
            obj.style.visibility == 'hidden';
        else
            obj.style.display = 'none';
    }
}


function ReOrderStars(StarIds, ImageIndexs) {
    _call("OrderStars", { "StarIds": StarIds, "ImageIndexs": ImageIndexs });
}

function DeleteAd(AdId, Control, UserKey) {
    var Panel = document.getElementById(Control);
    Panel.style.display = 'none';
    _call("DeleteUserAdds", { "AdId": AdId, "UserKey": UserKey });
}

function DeleteAllAdds(Control_Id, GenericLightBox, UserKey) {
    var control = document.getElementById(Control_Id);
    var v = control.getElementsByTagName("input");
    var ids = new Array();
    var temp = new String();
    for (var i = 0; i < v.length; i++) {
        if (v[i].type == "checkbox") {

            temp = new String();
            temp = v[i].id.split('chk_').toString();
            temp = temp.replace(',', '')
            ids[i] = temp;
            if (temp != '') {
                ids[i] = temp;
            }
        }
    }

    control.style.display = 'none';
    _call("DeleteMulitUserAdds", { "AdsId": ids, "UserKey": UserKey });
    HideLightBox(GenericLightBox);
}

function PrintChackedAds(ad_section, search_type, save_delete, GridId) {
    var GridControl = document.getElementById(GridId);
    var elements = GridControl.document.getElementsByTagName("input");
    var ids = new Array();
    var temp = new String();
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox" && elements[i].checked) {
            //elements[i].checked = false;
            temp = new String();
            temp = elements[i].id.split('chk_').toString();
            temp = temp.replace(',', '')
            ids[i] = temp;
            if (temp != '') {
                ids[i] = temp + ',';
            }
        }
    }

    var id = new String();
    for (var i = 0; i < ids.length; i++) {
        if (ids[i] != undefined) {
            id += ids[i];
        }
    }

    if (id.length <= 10) {
        url_path = "PrintAd.aspx?pid=" + id + "&cnt=" + 1 + "&sm=" + ad_section + "&t=" + search_type + "&ad_t=" + save_delete;
    }
    else {
        url_path = "PrintAd.aspx?pid=" + id + "&cnt=" + ids.length + "&sm=" + ad_section + "&t=" + search_type + "&ad_t=" + save_delete;

    }

    var ms = new mesureScreen(url_path);
    if (id.length > 0) {
        ms.openWindowWithScroll();
    }
}

function ChackChacked(GridId) {
    var Grid = document
}

function printChecked(ad_section, search_type, save_delete) {
    var elements = document.getElementsByTagName("input")
    var ids = new Array();
    var temp = new String();
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox" && elements[i].checked) {
            elements[i].checked = false;
            temp = new String();
            temp = elements[i].id.split('chk_').toString();
            temp = temp.replace(',', '')
            ids[i] = temp;
            if (temp != '') {
              ids[i] = temp + ',';
            }
        }
    }

    var id = new String();
    for (var i = 0; i < ids.length; i++) {
        if (ids[i] != undefined) {
            id += ids[i];
        }
    }

    if (id.length <= 10) {
        url_path = "PrintAd.aspx?pid=" + id + "&cnt=" + 1 + "&sm=" + ad_section + "&t=" + search_type + "&ad_t=" + save_delete;
    }
    else {
        url_path = "PrintAd.aspx?pid=" + id + "&cnt=" + ids.length + "&sm=" + ad_section + "&t=" + search_type + "&ad_t=" + save_delete;
        
    }

    var ms = new mesureScreen(url_path);
    if (id.length > 0) {
        ms.openWindowWithScroll();
    }
}

function CheckIsChecked(ButtonPrint, GridId) {
    var GridControl = document.getElementById(GridId);
    var elements = GridControl.document.getElementsByTagName("input");
    var ids = new Array();
    var flag = false;
    var btn_print = document.getElementById(ButtonPrint);
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].type == "checkbox" && elements[i].checked) {
            flag = true;
            break;
        }
    }

    if (flag) {
        btn_print.style.cursor = 'pointer';
    }
    else {
        btn_print.style.cursor = 'default';
    }
}


function ShowHide(DivName, ButtonName, LabelCategoryId) {
    var myDiv = document.getElementById(DivName);
    var BName = document.getElementById(ButtonName);
    var CategoryId = document.getElementById(LabelCategoryId);
    if (myDiv.style.display == "none") {
        _call("UpdateUserPreference", { "IsView": true, "Category": CategoryId.innerHTML });
        myDiv.style.display = "";
        BName.innerHTML = 'הסתר';
    }
    else {
        _call("UpdateUserPreference", { "IsView": false, "Category": CategoryId.innerHTML });
        myDiv.style.display = "none";
        BName.innerHTML = 'הצג';
    }
    return false;
}
 
function HandleContactUs(ptrAddNewContactUs, ptrShowHideLightBox, ptrClearInputs, TextBoxUserName, TextBoxEmail, DivID) {
    if (!eval(ptrAddNewContactUs))
        return false;
    eval(ptrClearInputs);
    eval(ptrShowHideLightBox);
    SetUserNameAndEmail(TextBoxUserName, TextBoxEmail);
    return false;
}
function GetTextBoxValue(TextBoxID) {
    var v = document.getElementById(TextBoxID);
    if (v != null)
        return v.value;
    else
        return null;

}
function RegExValidate(regex, value) {
    var regx = new RegExp(regex);
    if (regx.test(value)) {
        return true;
    } 
    else {
        return false;
    }
}
function PutTextOnTextBox(TextBoxID, Text) {
    var v = document.getElementById(TextBoxID);
    v.value = "";
    v.value = Text;
    v.style.color = "red";
    v.onfocus = function() { v.value = ""; v.style.color = "black"; }
    v.onblur = function() { ChickTextBoxValue(TextBoxID, Text); }
}
function ChickTextBoxValue(TextBoxID, Text) {
    var v = document.getElementById(TextBoxID);
    if (v.value == Text) {
        v.value = "";
        v.style.color = "black";
        v.onblur = function() { }
        v.onfocus = function() { }
    }
    if(v.value == '')
        PutTextOnTextBox(TextBoxID, Text);
}
function ValidateTextBox(TextBoxID, Text) {
    if (GetTextBoxValue(TextBoxID) == '' || GetTextBoxValue(TextBoxID) == Text) {
        PutTextOnTextBox(TextBoxID, Text);
        return false;
    }
}
function AddNewContactUs(Subject, PhoneNumber, Message, LastName, FirstName, Company, Email) {
    var Continue = true;
    var dummy;
    dummy = ValidateTextBox(Message, "נא למלא תוכן פנייה");
    if (dummy == false) {
        Continue = false;
    }
    var dummy = ValidateTextBox(FirstName, "אנא הזן שם פרטי");
    if (dummy == false) {
        Continue = false;
    }
    if (GetTextBoxValue(PhoneNumber) != '') {
        var regex = "^[0][5][0]-\\d{7}|[0][5][2]-\\d{7}|[0][5][4]-\\d{7}|[0][5][7]-\\d{7}|[0][7][7]-\\d{7}|[0][2]-\\d{7}|[0][3]-\\d{7}|[0][4]-\\d{7}|[0][8]-\\d{7}|[0][9]-\\d{7}|[0][5][0]\\d{7}|[0][5][2]\\d{7}|[0][5][4]\\d{7}|[0][5][7]\\d{7}|[0][7][7]\\d{7}|[0][2]\\d{7}|[0][3]\\d{7}|[0][4]\\d{7}|[0][8]\\d{7}|[0][9]\\d{7}$";
        b = RegExValidate(regex, document.getElementById(PhoneNumber).value);
        if (!b) {
            Continue = false;
        }
    }
    b = ValidateTextBox(Email, "אנא הזן מייל");
    if (b) {
        regex = "^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$";
        b = RegExValidate(regex, document.getElementById(Email).value);
        if (!b) {
            Continue = false;
        }
    }
    
    if (Continue == true) {
        var sub = GetTextBoxValue(Subject);
        if (document.getElementById('contact_area3').style.display != 'none') {
            sub = 'פנייה בנושא פרסום';
            var company = GetTextBoxValue(Company);
            if (company.length > 0)
                sub += ' מחברת ' + company;
        }

        _call("AddNewContactUs", { "Subject": sub, "PhoneNumber": GetTextBoxValue(PhoneNumber), "Message": GetTextBoxValue(Message), "LastName": GetTextBoxValue(LastName), "FirstName": GetTextBoxValue(FirstName), "Email": GetTextBoxValue(Email) });
        return true;
    }
    else {
        return false;
    } 
}

function ShowHideLightBox(LightBoxHide, LightBoxShow, IsTimer) {
    HideLightBox(LightBoxHide);
    ShowLightBox(LightBoxShow, IsTimer);
}
function ClearCreateUser(ElementID, LinkButtonID, DivID) {
    var Element = document.getElementById(ElementID);
    Element.innerHTML = "";
    Element.style.display = "none";

    //LinkButton = document.getElementById(LinkButtonID);
    //ucLoginBar_ucLightBox_lnkCallLight
    //ucLoginBar_ucLightBox_lnkCallLight
    //LinkButton.style.display = "none";
    
//    var Div = document.getElementById(DivID);
    //    Div.attributes["class"].value = "";
//    Div.style.display = "none";

}
function convertCP2Char(textString) {
    var outputString = '';
    textString = textString.replace(/^\s+/, '');
    if (textString.length == 0) { return ""; }
    textString = textString.replace(/\s+/g, ' ');
    var listArray = textString.split(' ');
    for (var i = 0; i < listArray.length; i++) {
        var n = parseInt(listArray[i], 16);
        if (n <= 0xFFFF) {
            outputString += String.fromCharCode(n);
        } else if (n <= 0x10FFFF) {
            n -= 0x10000
            outputString += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
        } else {
            outputString += 'convertCP2Char error: Code point out of range: ' + dec2hex(n);
        }
    }
    return (outputString);
}

function dec2hex(textString) {
    return (textString + 0).toString(16).toUpperCase();
}

function convertpEsc2CP(textString) {
    // textstring: sequence of percent-escaped text
    CPstring = '';
    var outputString = "";
    var compte = 0;
    var n = 0;
    // remove all leading spaces
    textString = textString.replace(/^\s+/, '');
    if (textString.length == 0) { return ""; }
    // normalize all multiple spaces to a single space - note: there shouldn't be any spaces!
    textString = textString.replace(/\s+/g, ' ');
    // convert the whole string to percent escaped forms (to reduce work in coding)
    for (var j = 0; j < textString.length; j++) {
        if (textString.charAt(j) == '%') { outputString += textString.slice(j, j + 3); j += 2; }
        else { outputString += '%' + dec2hex(textString.charCodeAt(j)); }
    }
    textString = outputString; outputString = '';
    var listArray = textString.split('%');
    for (var i = 1; i < listArray.length; i++) { // runs from 1 to eliminate first % (produces null array item)
        var b = parseInt(listArray[i], 16);   // alert('b:'+dec2hex(b));
        switch (compte) {
            case 0:
                if (0 <= b && b <= 0x7F) {  // 0xxxxxxx
                    outputString += dec2hex(b) + ' ';
                }
                else if (0xC0 <= b && b <= 0xDF) {  // 110xxxxx
                    compte = 1;
                    n = b & 0x1F;
                }
                else if (0xE0 <= b && b <= 0xEF) {  // 1110xxxx
                    compte = 2;
                    n = b & 0xF;
                }
                else if (0xF0 <= b && b <= 0xF7) {  // 11110xxx
                    compte = 3;
                    n = b & 0x7;
                }
                else {
                    outputString += '!erreur ' + dec2hex(b) + '! ';
                }
                break;
            case 1:
                if (b < 0x80 || b > 0xBF) {
                    outputString += '!erreur ' + dec2hex(b) + '! ';
                }
                compte--;
                outputString += dec2hex((n << 6) | (b - 0x80)) + ' ';
                n = 0;
                break;
            case 2: case 3:
                if (b < 0x80 || b > 0xBF) {
                    outputString += '!erreur ' + dec2hex(b) + '! ';
                }
                n = (n << 6) | (b - 0x80);
                compte--;
                break;
        }
    }
    CPstring = outputString.replace(/ $/, '');

    var v = convertCP2Char(CPstring);
    return v;
}

function SetUserNameAndEmail(TextBoxUserName, TextBoxEmail) {
    var s = readCookie("LoginCookie");
    if (s == null)
        return;
    var arr = s.split('=');
    var UserName = convertpEsc2CP(arr[4]);
    var Email = arr[1].split('&')[0];
    _decryptUserName("UserName");
    if (_search) {
        _search = _search.split(';');
        document.getElementById(TextBoxUserName).value = _search[1];
        document.getElementById(TextBoxEmail).value = _search[0];
    }
}

function _decryptUserName(userSearch) {
    _call("DecryptUsersDetails", { "UserName": userSearch }, OnDecryptSuccess);
}
function OnDecryptSuccess(contex) {
    _search = contex;
}

function ShowLiteBox(LiteBoxId, PostId, SearchType, TextBoxUserNameID, TextBoxEmailID) {
    if (LiteBoxId == "SR_LightBox_SendToFriend_LightBox")
        ClearSendToFriend();
    else
        ClearHurtfulContens();
     
    var vPostId = document.getElementById("SendToFriend_PostId");
    var vLightBoxId = document.getElementById("SendToFriend_LiteBoxId");
    var vSearchType = document.getElementById("SendToFriend_SearchType");
    
    vPostId.setAttribute("value", PostId);
    vLightBoxId.setAttribute("value", LiteBoxId);
    vSearchType.setAttribute("value", SearchType);
    SetUserNameAndEmail(TextBoxUserNameID, TextBoxEmailID);
    ShowLightBox(LiteBoxId);
}

function ShowLoginSignIn(lightBoxId, txtNum) 
{
    if (txtNum) {
        var ctr = 0;
        var obj;
        while (obj = document.getElementById('lsi_txt_' + (++ctr))) {
            if (ctr == txtNum) {
                obj.style.display = '';
            }
            else
                obj.style.display = 'none';
        }
    }

    ShowLightBox(lightBoxId);
}

function ShowContactUs(lightBoxId, isadvertiser) {
    if (isadvertiser) {
        document.getElementById('contact_area1').style.display = 'none';
        document.getElementById('contact_area2').style.display = 'none';
        document.getElementById('contact_area3').style.display = '';
        if(document.getElementById('contact_area4'))
            document.getElementById('contact_area4').style.display = 'none';
    } else {
        document.getElementById('contact_area1').style.display = '';
        document.getElementById('contact_area2').style.display = '';
        document.getElementById('contact_area3').style.display = 'none';
        if (document.getElementById('contact_area4'))
            document.getElementById('contact_area4').style.display = '';
    }

    ShowLightBox(lightBoxId,false);
}


/*Cookie Handling Funcs*/
var pageFullyLoaded = false;

function createCookie(name,value,days) {
	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=/";
}

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 PrintPage() {
    window.print();
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

function addToExistingCookie(name,value){
    var str_values = readCookie(name);

    if (str_values == null)
        str_values = '';

    str_values += value + ",";
    createCookie(name,str_values,1);
}

function removeFromExistingCookie(name,value){
    var str_values = readCookie(name);
    
    if(str_values){
        str_values = str_values.replace(value + ",","");
        createCookie(name,str_values,1);
    }
}

function getControlUpperLevel(ctrl_id){
    var ctrl_levels = ctrl_id.split('_');
    var res = "";
    for (var i = 0; i < ctrl_levels.length - 1; i++)
        res += ctrl_levels[i] + "_";

    if (res.length > 0)
        res = res.substr(0, res.length - 1);

    return res;
}

function openWindow(URL, win_name, width, height, scrollbars) {
    var centerWidth = (window.screen.width - width) / 2;
    var centerHeight = (window.screen.height - height) / 2;
    var props = 'toolbar=no,location=no,directories=no,status=0,menubar=no,scrollbars=' + (scrollbars ? (scrollbars == true ? 'yes' : 'no') : 'no') + ',resizable=1,copyhistory=no,width=' + width + ',height=' + height + ',left=' + centerWidth + ',top=' + centerHeight;
    var win = window.open(URL, win_name, props);
    win.moveTo(centerWidth, centerHeight);
    win.focus();
}

function Click(obj_id){
   try{
    document.getElementById(obj_id).click();
   }catch(e){}
}

function PostBack(obj_id){
   try{
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm._doPostBack(obj_id,'');
   }catch(e){}
}

function close_all(obj_id) {
    var obj = document.getElementById(obj_id);
    var containers = obj.getElementsByTagName('div');

    for (var i = 0; i < containers.length; i++) {
        var container = containers[i];
        if (container.id.indexOf('_container') > 0) {
            var ad_id = container.id.replace('_container', '');
            var tr_obj = document.getElementById(ad_id);
           
            if (tr_obj && tr_obj.style.display != 'none') {
                ToggleDetails(ad_id);  
            }
        }
    }
}

function ToggleAd(PostId) {

    ToggleDetails(PostId);
    //var PostDiv = document.getElementById(PostId + '_container');
}

function ToggleDetails(obj_id,e) {
  if (!e) var e = window.event;
  var targ;

  try {
     targ = document.all ? e.srcElement : e.target;
  }
  catch (e) {
      targ = new Object;
      targ.type = '';
  }

  
  if(targ == null || targ == "" || targ.type != "image"){
      var obj = document.getElementById(obj_id);
      var c_obj = document.getElementById(obj_id + "_container");
      var row_obj = document.getElementById("list_item_" + obj_id);
      var display_value = document.all? "block" : "table-row";

      var ex = new Expander();
      ex.objId = obj_id + "_container";
      ex.velocity = 100;
      
      
      if(obj.style.display=='none')
      {
          addToExistingCookie('open-ads',obj_id);
          addToExistingCookie('clicked-ads',obj_id);

          row_obj.style.background = '#d6eac7';
          row_obj.onmouseout = function() {};


          obj.style.display = display_value;
          ex.startValue = 0;
          ex.endValue = c_obj.getElementsByTagName("table")[0].clientHeight;
          ex.execute();
          
           
      }    
      else
      {
          obj.style.display = 'none';
          c_obj.style.height = '0px';
          removeFromExistingCookie('open-ads', obj_id);
          
          row_obj.style.color = '#bbbbbb';
          row_obj.style.background = '#F8F7F5';
          row_obj.onmouseout = function() { ChangeBgCol(row_obj, '#F8F7F5') };

      } 
  }   
}

var old_bg_col;

function ChangeBgCol(obj,bg_col){
   //if (bg_col != old_bg_col) {
   //    old_bg_col = obj.style.backgroundColor;
   //}else{
   //    old_bg_col=null;
   //}cree
   
   obj.style.backgroundColor=bg_col;
}

function CancelBubble(e){
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}


/* Search results Functions */
function toggle_views() {
    var obj_r = document.getElementById("rows_view");
    var obj_g = document.getElementById("gallery_view");

    var display_style = document.all ? "block" : "table-row";

    obj_r.style.display = obj_r.style.display == "none" ? display_style : "none";
    obj_g.style.display = obj_g.style.display == "none" ? display_style : "none";

    document.getElementById("a_rows_view").style.display = obj_g.style.display;
    document.getElementById("a_gallery_view").style.display = obj_r.style.display;

    createCookie('results-view', obj_g.style.display == "none",365);

    if (obj_r.height && obj_g.height)
        obj_r.height = obj_g.height = '0px';
}

function getScrollY() {
    if (typeof (window.pageYOffset) == 'number') {
        return window.pageYOffset;
    } else if (document.body && document.body.scrollTop) {
        return document.body.scrollTop;
    } else if (document.documentElement && document.documentElement.scrollTop) {
        return document.documentElement.scrollTop;
    } else {
        return 0;
    }
}

function getScrollX() {
    if (typeof (window.pageXOffset) == 'number') {
        return window.pageXOffset;
    } else if (document.body && document.body.scrollLeft) {
        return document.body.scrollLeft;
    } else if (document.documentElement && document.documentElement.scrollLeft) {
        return document.documentElement.scrollLeft;
    } else {
        return 0;
    }
}

function getWindowHeight() {
    if (typeof (window.innerHeight) == 'number') {
        return window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
         return document.body.clientHeight;
    } else {
        return 0;
    }
}

function getWindowWidth() {
    if (typeof (window.innerWidth) == 'number') {
        return window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        return document.documentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        return document.body.clientWidth;
    } else {
        return 0;
    }
}

/* Image Gallery Functions */
var big_img_width = 250;
var big_img_height = 188;

var small_img_width = 80;
var small_img_height = 60;

function scroll(scr,panel_id,img_arr,first_cell_id){
   var panel_obj = document.getElementById(panel_id);
   var images_obj = new Array();
   var images_obj_all = panel_obj.getElementsByTagName("img");
   var links_obj = panel_obj.getElementsByTagName("a");
   var changed = true;
   var first_cell = eval(first_cell_id);

   for (var i = 0; i < images_obj_all.length; i++) {
       if (images_obj_all[i].src.indexOf('overlay-') == -1) {
           images_obj.push(images_obj_all[i]);
       }
   }

   first_cell += scr; 
   if(first_cell<0){
      first_cell=0; 
      changed = false;
   }           
      
   if(first_cell>(img_arr.length-images_obj.length)){
      first_cell=img_arr.length-images_obj.length;  
      changed = false;
   }   
   
    for(var i=0;i<images_obj.length;i++){
            images_obj[i].src = img_arr[first_cell + i];
            links_obj[i].href = img_arr[first_cell + i];
            images_obj[i].onload = null;

            setGallerySmallImage(images_obj[i]);
    }
    
    var loaded_cell = (scr>0)?images_obj.length-1:0;
    
    if(changed){
        setOpacity(images_obj[loaded_cell],0);
        try{
        images_obj[loaded_cell].onload =  fade_in(images_obj[loaded_cell]);
        }catch(e){}
    }
    
    eval(first_cell_id +'='+ first_cell);    
}

function setOpacity(obj,opacity){
    if (document.all && obj.cells) {
        for (var i = 0; i < obj.cells.length; i++) {
            obj.cells[i].opacity = opacity / 10;
            obj.cells[i].style.filter = "alpha(opacity=" + (opacity) + ")";
        }  
    } else {
        obj.opacity = opacity / 10;
        if (document.all) {//IE
            obj.style.filter = "alpha(opacity=" + (opacity) + ")";
        } else {
            obj.style.MozOpacity = opacity / 100;
        }	
    }
    
}

function fade_in(obj)
{
    
    var img_obj = (obj.id)?obj:document.getElementById(obj);
    var opacity = (img_obj.opacity)?img_obj.opacity+15:15;

    var fader = new Fader();
    fader.startValue = 0;
    fader.endValue = 100;
    fader.velocity = 10;
    fader.obj = img_obj.id;
    fader.execute();
    fader.onComplete = function() { };   
    
    //if(opacity>100) opacity=100;
    //setOpacity(img_obj,opacity);
    
    //f(opacity<100){
     //setTimeout("fade_in('"+img_obj.id+"')",100);
    //}
	
    return;
}


function fade_in1(obj , fade_interval) {

    var img_obj = (obj.id) ? obj : document.getElementById(obj);
    var opacity = (img_obj.opacity) ? img_obj.opacity + fade_interval : fade_interval;

    if (opacity > 100) opacity = 100;
    setOpacity(img_obj, opacity);

    if (opacity < 100) {
        setTimeout("fade_in('" + img_obj.id + "')", 500);
    }

    return;
}
function fade_out(obj, fade_interval) {
    var img_obj = (obj.id) ? obj : document.getElementById(obj);
    var opacity = (img_obj.opacity) ? img_obj.opacity + fade_interval : fade_interval;
   
    opacity = opacity == 100 ? opacity = 0 : opacity = 100;
    setOpacity(img_obj, opacity);
    if (opacity < 100) {
        setTimeout("fade_in('" + img_obj.id + "')", 500);
    }
    if (opacity == 100) {
        setTimeout("fade_out('" + img_obj.id + "')", 500);
    }
    setTimeout("SetToNormalOpacity('" + img_obj.id + "')", 2000);

   
    return;
}


function SetToNormalOpacity(obj) {
    
    var img_obj = (obj.id) ? obj : document.getElementById(obj);
    var opacity = (img_obj.opacity) ? img_obj.opacity + 15 : 15;
    var rec_counter = 3;
    img_obj.opacity = 100;

    if (opacity == 100) {
        setTimeout("fade_in('" + img_obj.id + "')", 500);
    }

    opacity = 0;
}


function iPreloader(img_arr, oncomplete) {
    this.allImages = [];
    this.loadedImages = [];
    this.errorImages = [];
    this.length = img_arr.length;
    this.cnt = 0;

    this.complete = oncomplete;


    for (var i = 0; i < this.length; i++) {
        var img = new Image();
        this.allImages.push(img);
        img.preloader = this;
        img.onload = function() {
            this.preloader.loadedImages.push(this.src);
            this.preloader.cnt++;
            if (this.preloader.cnt >= this.preloader.length)
                this.preloader.complete();
        };
        img.onerror = function() {
            this.preloader.errorImages.push(this.src);
            this.preloader.cnt++;
            if (this.preloader.cnt >= this.preloader.length)
                this.preloader.complete();
        };
        img.onabort = function() {
            this.preloader.cnt++;
            if (this.preloader.cnt >= this.preloader.length)
                this.preloader.complete();
        };

        img.src = img_arr[i];
    } 
}


iPreloader.prototype.preload = function(img_src) {

   
}

function setWorkingImage(img, img_arr) {
    img = typeof img == "object" ? img : document.getElementById(img);

    var p = new iPreloader(img_arr, function() {
        if (this.loadedImages.length > 0) { img.src = this.loadedImages[0]; } 
    }
    );
}

function setGalleryBigImage(img_id,src){
    var img = new Image();
    try{
        img.onload = function() {bigImageLoaded(this, img_id); };
    } catch (e) { }
    img.src = src;
}

function setGallerySmallImage(img_obj) {
    var img = new Image();
    try {
        img.onload = function() { smallImageLoaded(this,img_obj); };
    } catch (e) { }
    img.src = img_obj.src;
}

function setGalleryImage(img_obj) {
    var img = new Image();
    try {
        img.onload = function() { galleryImageLoaded(this, img_obj); };
    } catch (e) { }
    img.src = img_obj.src;
}


function bigImageLoaded(img, targ_id) {
  img_obj = document.getElementById(targ_id);
  
  link_obj = document.getElementById(targ_id.replace('img_b_', 'a_b_'));

  if (link_obj)
    link_obj.href = img_obj.src = img.src;

  var _d = getImageSize(img,big_img_width,big_img_height);

  var overlay_b = link_obj.parentNode.getElementsByTagName('div')[1];

  overlay_b.style.top = (_d.height - 25) + 'px';
  overlay_b.style.height = (big_img_height - _d.height + 27) + 'px';

  img_obj.width = _d.width;
  img_obj.height = _d.height;

}

function smallImageLoaded(img_obj, target_obj) {
    var _d = getImageSize(img_obj, small_img_width, small_img_height);

    target_obj.width = _d.width;
    target_obj.height = _d.height;

    var overlay_b = target_obj.parentNode.parentNode.getElementsByTagName('div')[1];

    overlay_b.style.top = (_d.height - 10) + 'px';
    overlay_b.style.height = (small_img_height - _d.height + 10) + 'px';
}


function galleryImageLoaded(img_obj, target_obj) {
    var gallery_img_width = parseInt(target_obj.parentNode.style.width);
    var gallery_img_height = parseInt(target_obj.parentNode.style.height);

    var _d = getImageSize(img_obj, gallery_img_width, gallery_img_height);

    target_obj.width = _d.width;
    target_obj.height = _d.height;

    var overlay_b = target_obj.parentNode.getElementsByTagName('div')[1];

    overlay_b.style.top = (_d.height - 20) + 'px';
    overlay_b.style.height = (gallery_img_height - _d.height + 20) + 'px';
}


function scanResizeImages() {
    var im_arr = document.getElementsByTagName('img');

    for (var i = 0; i < im_arr.length;  i++) {
        var im = im_arr[i];
        if (im.attributes["_rel"] && im.attributes["_rel"].value == "gallery") {
            var im_tmp = new Image();
            im_tmp.origimg = im;

            im_tmp.onload = function() {
                var _d = getImageSize(this,big_img_width,big_img_height);
                this.origimg.width = _d.width;
                this.origimg.height = _d.height;
            }
            im_tmp.src = im.src;
            
        }
    }
}

function getImageSize(img, max_img_width, max_img_height) {
    var img_width = img.width;
    var img_height = img.height;
    var img_delta = img_width / img_height;

    if (img_width > max_img_width) {
        img_width = max_img_width;
        
        img_height = max_img_width / img_delta;
    }

    if (img_height > max_img_height || img_height == 0) {

        img_height = max_img_height;
        img_width = max_img_height * img_delta;
    }
    
    
    if (img_width == 0) {
        img_width = max_img_width;
        img_height = '100%';
    }

    return { width: img_width, height: img_height };
}

function InitGallery(panel_id,big_img_id,img_arr,scroll_left,scroll_right){
   var panel_obj = document.getElementById(panel_id);
   var links_obj = panel_obj.getElementsByTagName("a");
   
   var arr_cnt = img_arr.length;
   
   if(arr_cnt<=3){
        document.getElementById(scroll_left).style.display='none';  
        document.getElementById(scroll_right).style.display='none'; 
   }else{
        document.getElementById(scroll_left).style.display = '';
        document.getElementById(scroll_right).style.display = ''; 

        arr_cnt=3;
   }

   if (arr_cnt > 0) {
       setGalleryBigImage(big_img_id, img_arr[0]);
   } else {
        var href_obj = document.getElementById(big_img_id).parentNode;
        href_obj.setAttribute("rel", "");
        href_obj.setAttribute("onclick", "return false;");
   }

   for (var i = 0; i < links_obj.length; i++)
       links_obj[i].parentNode.style.display = 'none';

   for (var i = 0; i < arr_cnt; i++) {
       links_obj[i].parentNode.style.display = '';

       var img_obj = links_obj[i].getElementsByTagName("img")[0];
       img_obj.src = img_arr[i];

       setGallerySmallImage(img_obj);
       
       links_obj[i].href = img_arr[i];
   }    
}



function Toggle(toggler, toggler_open_bg,toggler_close_bg, toggled) {
    toggler = typeof toggler == "object" ? toggler : document.getElementById(toggler);
    toggled = typeof toggled == "object" ? toggled : document.getElementById(toggled);

    toggled.style.display = toggled.style.display == 'none' ? '' : 'none';
    toggler.style.backgroundColor = toggled.style.display == 'none' ? toggler_close_bg : toggler_open_bg; 
}


/* Comment-Detail panels */
function togglePanel(panel_id,image_id,open_img_src,close_img_src,close_obj_arr){
    var panel_obj = document.getElementById(panel_id);
    var image_obj = document.getElementById(image_id);
    var img_src;

    if(panel_obj.style.display!='none'){
       panel_obj.style.display='none';
       img_src = close_img_src;
    }else{
       panel_obj.style.display='';
       img_src = open_img_src;
    }
    
    if(image_obj)
       image_obj.src =  img_src;

    if(close_obj_arr){
        for(var i=0;i<close_obj_arr.length;i=i+2){
            var tmp_obj = document.getElementById(close_obj_arr[i]);
            var tmp_img = document.getElementById(close_obj_arr[i+1]);
            if(tmp_obj && tmp_obj.style.display!='none'){
                tmp_obj.style.display = 'none';
                tmp_img.src = close_img_src;
            }   
        }
    }
}


/*Light box functions*/

function ShowLightBox(modal_popup_id, IsTimer) {

    var obj = $find(modal_popup_id);

    if (obj) {
        obj.show();
    }
    if (IsTimer) {
        setTimeout("HideLightBox('" + modal_popup_id + "')", 3000);
    }
}

function ShowLightSmsBox(modal_popup_id, IsTimer,IsValid) {
    var obj = $find(modal_popup_id);    
    if (obj) {
        obj.show();
        //alert(modal_popup_id);
    }
    if (IsTimer) {
        setTimeout("HideLightBox('" + modal_popup_id + "')", 3000);
    }
    return IsValid;
}

function HideLightBox(modal_popup_id) {
    var obj = $find(modal_popup_id);
    if (obj) {
        obj.hide();
    }
}

function _HideLightBox() {
    document.getElementById('blockUI').style.display = "none";
    return false;
}

function ClearUEmail() {
    eval("document.forms[0].ucLoginBar_ucLightBox_FirstStep_txtUEmail.value = \'\'");
}

function ClearUName() {
    eval("document.forms[0].ucLoginBar_ucLightBox_FirstStep_txtUName.value = \'\'");
}

function ClearOrigPassword() {
    eval("document.forms[0].ucLoginBar_ucLightBox_FirstStep_txtOrigPassword.value = \'\'");
}

function ClearRedoPassword() {
    eval("document.forms[0].ucLoginBar_ucLightBox_FirstStep_txtRedoPassword.value = \'\'");
}
function ClearUserEmail() {
    eval("document.forms[0].ucLoginBar_ucLightBox_SignIn_txtUEmail.value = \'\'");
}
/*Dynamic Population Functions*/

function _populate(populate_obj_id, value) {
    var _dp = $find(populate_obj_id);
    
    if (_dp) {
        _dp.populate(value);
    }
}

function FixSubScript(scr) {
    alert(scr);

    var rx = /[.*]\'[\w\s\d]*\([\w\s\d\'\,\(\)]*\)\'/g;
    var scr_tmp = scr;
    var in_str = rx.exec(scr_tmp);

    //alert(in_str);
    
    if (in_str) {
        var tmp_str = in_str[0].substr(1, in_str.length - 2);
        tmp_str = tmp_str.replace(/\'/g, "`");
        scr_tmp = scr_tmp.replace(in_str[0], "'" + tmp_str + "'");
    }
    return scr_tmp;
}

function PopulateSearchControl(populate_obj_id,search_type,populating_control_id,selected_values){
      var val = search_type+";"+populating_control_id+";"+selected_values;
      _populate(populate_obj_id, val);
}


function GetControlValues(obj_id) {
    var ob_ar = [];

    var main_obj = obj_id ? document.getElementById(obj_id) : document;

    var objs = main_obj.getElementsByTagName("div");
    for (var i = 0; i < objs.length; i++) {
        if (objs[i].id.indexOf("d_") == 0)
            ob_ar.push(objs[i]);
    }

    objs = main_obj.getElementsByTagName("span");
    for (var i = 0; i < objs.length; i++) {
        if (objs[i].id.indexOf("d_") == 0)
            ob_ar.push(objs[i]);
    }

    //alert(ob_ar.length);
    
    var text_obj = document.getElementById("s_free_Text");
    var str_res = '';

    for (var i = 0; i < ob_ar.length; i++) {
        var obj = ob_ar[i];
        var sub_field = '';

        var c_name = tmp_c_name = obj.id.substring(2);
        
        var str_res_tmp = '';
        var inps = obj.getElementsByTagName('input');
        
        if (inps) {
            for (var j = 0; j < inps.length; j++) {
                var inp = inps[j];
                switch (inp.type) {
                    case 'checkbox':
                        if (inp.checked && inp.value && inp.value != 'on' && inp.value != '') {
                            if (inp.name.indexOf('^') < 0) {
                                str_res_tmp += inp.value + ',';
                            }
                            else {
                                sub_field = inp.name;
                            }
                        }
                        break;
                    case 'radio':
                        if (inp.value && inp.value != 'on' && inp.value != '') {
                            if (inp.id.indexOf("c_1_") == 0 && inp.checked) {
                                str_res_tmp = inp.value + str_res_tmp;
                            } else if (inp.id.indexOf("c_2_") == 0 && inp.checked) {
                                str_res_tmp += (str_res_tmp = '' ? "," + str_res_tmp : ",") + inp.value;
                            } else if (inp.name.indexOf("r_") == 0 && inp.checked) {
                                tmp_c_name = inp.value;
                            } else if (inp.checked) {
                                str_res_tmp += inp.value;
                            }
                        }
                        break;
                    case 'text':
                        if (inp.id.indexOf("c_1_") == 0 && inp.value != '' && (!inp.attributes["_def"] || (inp.attributes["_def"] && inp.attributes["_def"].value != inp.value))) {
                            str_res_tmp = inp.value.replace(/,/g,'') + str_res_tmp;
                        } else if (inp.id.indexOf("c_2_") == 0 && inp.value != '' && (!inp.attributes["_def"] || (inp.attributes["_def"] && inp.attributes["_def"].value != inp.value))) {
                            str_res_tmp += (str_res_tmp = '' ? "," + str_res_tmp : ",") + inp.value.replace(/,/g, '');
                        }
                       
                        break;
                    case 'hidden':
                        if (inp.id.indexOf("c_1_") == 0) {
                            str_res_tmp = inp.value + str_res_tmp;
                        } else if (inp.id.indexOf("c_2_") == 0) {
                            str_res_tmp += (str_res_tmp = '' ? "," + str_res_tmp : ",") + inp.value;
                        }
                        else if (inp.id.indexOf("ty_") != 0 && inp.value != '') {
                            str_res_tmp += inp.value;
                        }
                        break;
                }
                
            }
        } else if (c_name == 'free_Text') {
            str_res_tmp = document.getElementById("s_free_Text").value;
        }
        
        
        if (str_res_tmp.length > 0) {
            str_res += "&" + tmp_c_name + "=" + (str_res_tmp.charAt(str_res_tmp.length - 1) == ',' ? str_res_tmp.substring(0, str_res_tmp.length - 1) : str_res_tmp);
            str_res += "&ty_" + tmp_c_name + "=" + document.getElementById("ty_" + c_name).value;
        }


        if (sub_field.length > 0) {
            str_res_tmp = '';
            tmp_c_name = sub_field.split('^')[1];

            var sub_inps = document.getElementsByName(sub_field);

            for (var k = 0; k < sub_inps.length; k++) {
                if (sub_inps[k].type == "checkbox" && sub_inps[k].checked && sub_inps[k].value && sub_inps[k].value != 'on' && sub_inps[k].value != '') {
                    //if (sub_inps[k].value.indexOf('^') > 0)
                    //    str_res_tmp += sub_inps[k].value.split('^')[1] + ',';
                    //else
                        str_res_tmp += sub_inps[k].value + ',';
                }
            }
            
            if (str_res_tmp.length > 0) {
                str_res += "&" + tmp_c_name + "=" + (str_res_tmp.charAt(str_res_tmp.length - 1) == ',' ? str_res_tmp.substring(0, str_res_tmp.length - 1) : str_res_tmp);
                str_res += "&ty_" + tmp_c_name + "=" + document.getElementById("ty_" + c_name).value;
            }
        }
    }

    if (text_obj && text_obj.value && text_obj.value != '') {
        str_res += "&free_Text=" + text_obj.value;
        str_res += "&ty_free_Text=" + document.getElementById("ty_free_Text").value;
    }
    //objs = obj.getElementsByTagName('input');
    
    return(str_res);
}



/* Web Methods Functions */

function _call(method, params,succeeded_func,user_context) {
    Sys.Net.WebServiceProxy.invoke("Populate.asmx", method, false, params, succeeded_func, _callFailed, user_context, 100000000);
}
function _callSucceeded(result, userContext, methodName) {
    //alert(result);
}

function _callFailed(result) {

//      alert(result);
//    alert();
}

function count_results(search_type, population_obj_id, is_large, values) {
    _call("CountResults", { "SearchType": search_type, "IsLarge": is_large, "SelectedValues": values }, count_results_success, population_obj_id);
}
 
function count_results_success(result, user_context) {
    var obj = document.getElementById(user_context);
    obj.innerHTML = result;
}



function get_control(search_type, populating_control_id, selected_value, population_function, for_publish) {
    _call("ControlPopulate", { "SearchType": search_type, "ControlId": populating_control_id, "Selected": selected_value, "PopulationMethod": population_function, "ForPublish": for_publish ? for_publish : false }, get_control_success, for_publish);
}

function get_control_success(result, user_context) {
    var _o = eval('(' + result + ')');
    
    var i = 0, id, html, script;

    while (id = eval('_o.id'+i)) {
        html = eval('_o.html' + i);
        script = eval('_o.script' + i);
        
        var obj = _get('t_' + id);
        while (!user_context && obj.parentNode.nodeName.toLowerCase() != 'span')
            obj = obj.parentNode;
        obj = obj.parentNode;
        obj.innerHTML = HtmlDecodeLite(html);

        if (script)
            eval(script);
        toolTip.initelements(obj);

        if (user_context) {
            var val_obj = _get("c_" + id) ? _get("c_" + id) : _get("s_" + id);
            validate(val_obj);
        }
        i++;
    }
}

function get_details(search_type, area, ad_id, LiteBox1Id, LiteBox2Id, LightBox3Id, s_id) {
    var obj = document.getElementById(ad_id + "_container");

    if (obj.innerHTML == '') {
        _call("GetAdDetails", { "SearchType": search_type, "Area": area, "AdId": ad_id, "LiteBox1Id": LiteBox1Id, "LiteBox2Id": LiteBox2Id, "LightBox3Id": LightBox3Id, "SearchId": s_id ? s_id : 0}, get_details_success, ad_id);
    } else {
        ToggleDetails(ad_id);
    }

    while (obj.parentNode.nodeName.toLowerCase() != 'table')
        obj = obj.parentNode;

    return obj.parentNode.id.substring(0, obj.parentNode.id.length - 4);
}

function get_details_success(result, user_context) {
    var obj = document.getElementById(user_context + "_container");
    obj.innerHTML = result;
    appendInnerScript(obj.id);

    if (cl.hascommand) {
        cl.pull();
    }

    if (CallServer)
        CallServer('');
        
    ToggleDetails(user_context);
    SetGallery(user_context);

}

function SetGallery(ad_id) {
    var p = new iPreloader(eval("img_array_" + ad_id),
                           function() {
                                eval('img_array_' + ad_id + ' = this.loadedImages');
                                eval("InitGallery('s_img_" + ad_id + "','img_b_" + ad_id + "',img_array_" + ad_id + ",'scr_l_" + ad_id + "','scr_r_" + ad_id + "');");
                           }
    );
}

function delete_get_next_ad(r, t, id, c, s, p, f, d, a, g) {
    _call("DeleteGetNextAd", { "r": r, "t": t, "id": id, "s": s, "p": p, "f": f, "d": d, "a": a, "g": g, "c": c }, ad_delete_success, id);
}

function get_next_ad_success(result, user_context) {
    var ad_obj = eval('(' + result + ')');

    //if (ad_obj.DeletedAdId && ad_obj.DeletedAdId > 0) {
    //    ad_delete_success('', ad_obj.DeletedAdId);
    //}
    if (ad_obj.Row1) {
        
    
        var tbl_obj = document.getElementById(ad_obj.AffectedControl + '_grv').tBodies[0];

        var row_1 = tbl_obj.rows[tbl_obj.rows.length - 3].cloneNode(true);
        var row_2 = tbl_obj.rows[tbl_obj.rows.length - 2].cloneNode(true);
        var row_3 = tbl_obj.rows[tbl_obj.rows.length - 1].cloneNode(true);

        tbl_obj.appendChild(row_1);
        tbl_obj.appendChild(row_2);
        tbl_obj.appendChild(row_3);

        row_1.id = 'list_item_' + ad_obj.AdId;
        row_2.id = ad_obj.AdId;
        row_3.id = 'spcr_' + ad_obj.AdId;



        var i = 1;
        while (eval("ad_obj.Row" + i) || eval("ad_obj.Row" + i) == '') {
            row_1.cells[i].innerHTML = HtmlDecode(eval("ad_obj.Row" + i));
            i++;
        }

        var a_event = row_1.attributes["onclick"].value.split(',');
        a_event[2] = ad_obj.AdId;
        row_1.attributes["onclick"].value = a_event.join(",");

        row_2.getElementsByTagName('div')[0].id = ad_obj.AdId + '_container';
    } 
    else if (ad_obj.AdText) {

        var tbl_obj = document.getElementById(ad_obj.AffectedControl + '_lst').getElementsByTagName('table')[0];
        var cell = tbl_obj.rows[0].cells[0].cloneNode(true);
        var prev_id = cell.id.replace('gallery_item_', '');

        //alert(cell);
        
        cell.id = 'gallery_item_' + ad_obj.AdId;
        cell.innerHTML = cell.innerHTML.replace(eval('/' + prev_id + '/g'), ad_obj.AdId);

        tbl_obj.rows[tbl_obj.rows.length - 1].appendChild(document.createElement('td'));
        tbl_obj.rows[tbl_obj.rows.length-1].appendChild(cell);
        
        

        var c = cell.getElementsByTagName('img');

        c[0].src = ad_obj.AdImage;
        c[3].src = ad_obj.UserComment != '' ? 'img/remark-on.gif' : 'img/remark-off.gif';
        c[3].setAttribute("_tooltip", ad_obj.UserComment);
        cell.getElementsByTagName('a')[0].innerHTML = HtmlDecode(ad_obj.AdText);
        cell.getElementsByTagName('span')[0].innerHTML = HtmlDecode(ad_obj.AdDate);

    }


    var lbl_obj = document.getElementById(ad_obj.AffectedControl + '_lblRes');
    lbl_obj.innerHTML = HtmlDecode(ad_obj.InfoText);
    
    
    var p_c = ad_obj.PageCount;
    var p_t = document.getElementById(ad_obj.AffectedControl + '_T_Page_0');
    var p_b = document.getElementById(ad_obj.AffectedControl + '_B_Page_0');
    
    if (p_t) {
        var p_t = p_t.parentNode;
        var p_b = p_b.parentNode;
        if (p_c < 2) {
            var t_r = p_t.parentNode;
            var b_r = p_b.parentNode;


            t_r.cells[0].innerHTML = t_r.cells[1].innerHTML = t_r.cells[2].innerHTML =
            b_r.cells[0].innerHTML = b_r.cells[1].innerHTML = b_r.cells[2].innerHTML = '';
        }
        p_t = p_t.getElementsByTagName('a');
        p_b = p_b.getElementsByTagName('a');

        while(p_t[p_c]){
            p_t[p_c].parentNode.removeChild(p_t[p_c]);
            p_b[p_c].parentNode.removeChild(p_b[p_c]);
        }    
    }
    
}

function HtmlDecode(s) {
    var out = "";

    if (s == null) return;
    var l = s.length;

    for (var i = 0; i < l; i++) {
        var ch = s.charAt(i);
        if (ch == '&') {
            var semicolonIndex = s.indexOf(';', i + 1);

            if (semicolonIndex > 0) {
                var entity = s.substring(i + 1, semicolonIndex);
                if (entity.length > 1 && entity.charAt(0) == '#') {
                    if (entity.charAt(1) == 'x' || entity.charAt(1) == 'X')
                        ch = String.fromCharCode(eval('0' + entity.substring(1)));
                    else
                        ch = String.fromCharCode(eval(entity.substring(1)));
                } else {
                    switch (entity) {
                        case 'quot': ch = String.fromCharCode(0x0022); break;
                        case 'amp': ch = String.fromCharCode(0x0026); break;
                        case 'lt': ch = String.fromCharCode(0x003c); break;
                        case 'gt': ch = String.fromCharCode(0x003e); break;
                        case 'nbsp': ch = String.fromCharCode(0x00a0); break;
                        default: ch = ''; break;
                    }

                }
                i = semicolonIndex;
            }
        }
        out += ch;
    }
    return out;
}

function HtmlDecodeLite(s) 
{
    var tmp = s;

    tmp = tmp.replace(/\&quot\;/g, String.fromCharCode(0x0022));
    tmp = tmp.replace(/\&amp\;/g, String.fromCharCode(0x0026));
    tmp = tmp.replace(/\&lt\;/g, String.fromCharCode(0x003c));
    tmp = tmp.replace(/\&gt\;/g, String.fromCharCode(0x003e));
    tmp = tmp.replace(/\&nbsp\;/g, String.fromCharCode(0x00a0));

    return tmp;
}


//insert preffered type
function Preffered(post_id, ad_section, preffered_search) {
    _call("InsertPreffered", { "PostID": post_id, "AD_SECTION": ad_section, "PREFFERED_SEARCH": preffered_search }, insert_preffered_success);
}
function Preffered2(count, ad_section, preffered_search) {
    _call("InsertPreffered2", { "Count": count, "AD_SECTION": ad_section, "PREFFERED_SEARCH": preffered_search }, insert_preffered_success);
}

function insert_preffered_success(result) {
    
}
function reload_control(search_type, control_id, selected_categories, selected_values, sub_selected_values, population_function, for_publish) {
    _call("ControlReload", { "SearchType": search_type, "ControlId": control_id, "SelectedCategories": selected_categories, "SelectedValues": selected_values, "SubSelectedValues": sub_selected_values, "PopulationMethod": population_function, "ForPublish" : for_publish ? for_publish : false }, reload_control_success, for_publish);
}

function reload_saved_messages_control() {

    _call("ReloadSavedMessages", {}, 'reload_saved_messages_Success');
}

function ReloadControlSM(category) {
    _call("ReloadSavedMessages", { "Category": category }, reload_saved_messages_Success);
}

function ReloadControlSavedMessages(category) {
    _call("ReloadSavedMessages", { "Category": category }, saved_messages_Success);
}

function saved_messages_Success(result, user_context) {
    var obj = document.getElementById("loadControl");
    if (obj) {
        obj.innerHTML = result;
        toolTip.initelements(obj);
    }
}

function reload_saved_messages_Success(result, user_context) {
    var obj = document.getElementById("loadControl");
    if (obj) {
        obj.innerHTML = result;
        ///fade_in1(obj,1);
        // fade_out(obj,1);
        var fad_obj = document.getElementById("objFader");

        if (fad_obj) {
            Blink(fad_obj, 4);
        }
    }
}

function Blink(obj,times) {
    if (times > 0) {
        var fader_out = new Fader();
        fader_out.startValue = 100;
        fader_out.endValue = 40;
        fader_out.velocity = 20;
        fader_out.obj = obj.id;
        fader_out.onComplete = function() {
            var fader_in = new Fader();
            fader_in.startValue = 40;
            fader_in.endValue = 100;
            fader_in.velocity = 20;
            fader_in.obj = obj.id;
            fader_in.onComplete = function(){ Blink(obj, --times);};
            fader_in.execute();
        }
        fader_out.execute();
    }
}

function reload_control_success(result, user_context) {
    var ad_obj = eval('(' + result + ')');

    var obj = document.getElementById('t_' + ad_obj.id);
    if (obj) {
        while (!user_context && obj.parentNode.nodeName.toLowerCase() != 'span')
            obj = obj.parentNode;
       
        obj = obj.parentNode;
        obj.innerHTML = HtmlDecodeLite(ad_obj.html);

        toolTip.initelements(obj);

    }
    if (ad_obj.script && ad_obj.script != '') {
        var script = ad_obj.script;
        eval(script);
    }

}


function ad_save(ad_id) {
    _call("SaveAd", { "adId": ad_id }, ad_save_success);
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
function ad_save_success(result) {
    var save_button_1 = document.getElementById('btn_save_ad_' + result);
    var save_canel_button_1 = document.getElementById('btn_save_ad_cancel_' + result);
    
    var save_button_2 = document.getElementById('btn_save_ad_row_' + result);
    var save_canel_button_2 = document.getElementById('btn_save_ad_row_cancel_' + result);

    var save_button_3 = document.getElementById('btn_save_ad_gal_' + result);
    var save_canel_button_3 = document.getElementById('btn_save_ad_gal_cancel_' + result);
    
    try{
        save_button_1.style.display = 'none';
        save_canel_button_1.style.display = 'inline'
    }catch(ex){}

    try {
        save_button_2.style.display = 'none';
        save_canel_button_2.style.display = 'inline'
    } catch (ex) { }

    try {
        save_button_3.style.display = 'none';
        save_canel_button_3.style.display = 'inline'
    } catch (ex) { }    

    IsReloadAlowed();
}


//if cookie contains only user id than
//it's not alowed to save messages 
//otherwise it's OK!
function IsReloadAlowed() {
    var IsAlowedToAdd = false;
    var query = getCookie('DefaultCookie');
    var pairs = query.split("=&");
    var value = "";
    var args = new Array(3);
    
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        args[i] = argname;
        value = pairs[i].substring(pos + 1);
    }
    var login = getCookie('LoginCookie');
    if (login != "") {
        ReloadControlSM(LoadCategoryType());
    }
    else {
        if (args[0] == undefined && args[1] == undefined && args[2] != undefined) {
            ReloadControlSM(LoadCategoryType());
        }
    }
    
}

function ad_save_cancel(ad_id,hiderow) {
    _call("SaveAdCancel", { "adId": ad_id }, (hiderow && hiderow == true) ? ad_delete_success : ad_save_cancel_success, ad_id);
}


function del_ad(ad_id) {
    _call("SaveAdCancel", { "adId": ad_id }, ad_save_cancel_success);
}
function del_save_cancel_success(result) {
    var obj = document.getElementById("loadControl");
    if (obj) {
    
        ReloadControlSavedMessages(LoadCategoryType());
        //ReloadControlSavedMessages(category);
    }
   // Blink(obj, 3)
}

function ad_save_cancel_success(result) {
    var ad_obj = eval('(' + result + ')');

    var save_button_1 = document.getElementById('btn_save_ad_' + ad_obj.DeletedAdId);
    var save_canel_button_1 = document.getElementById('btn_save_ad_cancel_' + ad_obj.DeletedAdId);

    var save_button_2 = document.getElementById('btn_save_ad_row_' + ad_obj.DeletedAdId);
    var save_canel_button_2 = document.getElementById('btn_save_ad_row_cancel_' + ad_obj.DeletedAdId);

    var save_button_3 = document.getElementById('btn_save_ad_gal_' + ad_obj.DeletedAdId);
    var save_canel_button_3 = document.getElementById('btn_save_ad_gal_cancel_' + ad_obj.DeletedAdId);


    try {
        save_button_1.style.display = 'inline';
        save_canel_button_1.style.display = 'none'
    } catch (ex) { }

    try {
        save_button_2.style.display = 'inline';
        save_canel_button_2.style.display = 'none'
    } catch (ex) { }

    try {
        save_button_3.style.display = 'inline';
        save_canel_button_3.style.display = 'none'
    } catch (ex) { }

    ReloadControlSM(LoadCategoryType());
}

function ad_delete(ad_id) {
    _call("DeleteAd", { "adId": ad_id }, ad_delete_success,ad_id);
}


function ad_delete_cancel(ad_id) {
    _call("DeleteAdCancel", { "adId": ad_id }, ad_delete_success,ad_id);
}

function ad_delete_success(result, user_context) {
    var ad_obj = eval('(' + result + ')');

    var obj = document.getElementById('list_item_' + ad_obj.DeletedAdId);
    var obj_gallery = document.getElementById('gallery_item_' + ad_obj.DeletedAdId);
    var obj_details = document.getElementById(ad_obj.DeletedAdId);
    var obj_spacer = document.getElementById('spcr_' + ad_obj.DeletedAdId);
    //obj.parentNode.removeChild(obj);
    
    var ex = new Fader();
    ex.startValue = 100;
    ex.endValue = 0;
    ex.velocity = 30;
    //ex.obj = [obj_details, obj, obj_gallery]; //gallery view

    if (obj) {
        ex.obj = [obj_details, obj, obj_spacer];
        ex.onComplete = function() {
            ex.obj[0].parentNode.removeChild(ex.obj[0]);
            ex.obj[1].parentNode.removeChild(ex.obj[1]);
            ex.obj[2].parentNode.removeChild(ex.obj[2]);

            get_next_ad_success(result);
        }
    } else if (obj_gallery) {
       
        ex.obj = [obj_gallery];
        ex.onComplete = function() {
            var t_obj = ex.obj[0].parentNode;
            
            var elem = ex.obj[0].nextSibling;
            while (elem.innerHTML == null) {
                elem = elem.nextSibling;
            }
            t_obj.removeChild(elem);


            t_obj.removeChild(ex.obj[0]);

           
            
            while (t_obj && t_obj.nodeName != 'TABLE')
            t_obj = t_obj.parentNode;

            
            var rows_arr = t_obj.rows;
            for (var i = 0; i < rows_arr.length - 2; i += 2) {
                if (rows_arr[i].cells.length < 9) {
                    rows_arr[i].appendChild(rows_arr[i + 2].cells[1]);
                    rows_arr[i].appendChild(rows_arr[i + 2].cells[0]);
                }
            }

            get_next_ad_success(result);
            
        }
    }

    ReloadControlSavedMessages(LoadCategoryType());

    ex.execute();

}

function ad_bump(ad_id) {
    _call("BumpAd", { "AdId": ad_id }, ad_bump_success, ad_id);
}

function ad_bump_success(result, user_context) {
    if (_get('lBumpAd_PanelLightBox')) {
        ShowLightBox('lBumpAd_LightBox',true);
    }
}

function ad_freese(ad_id, date) {
    _call("FreeseAd", { "AdId": ad_id, "Date": date }, ad_freese_success, ad_id);
}

function ad_freese_success(result, user_context) {
    if (_get('lFreeseAd_PanelLightBox')) {
        HideLightBox('lFreeseAd_LightBox');
        window.location.reload();
    }
}

function ad_unfreese(ad_id) {
    _call("UnFreeseAd", { "AdId": ad_id }, ad_unfreese_success, ad_id);
}

function ad_unfreese_success(result, user_context) {
    if (_get('lFreeseAd_PanelLightBox')) {
        window.location.reload();
    }
}

function ad_remove(ad_id) {
    _call("RemoveAd", { "AdId": ad_id }, ad_remove_success, ad_id);
}

function ad_remove_success(result, user_context) {
    if (_get('lRemoveAd_PanelLightBox')) {
        HideLightBox('lRemoveAd_LightBox');
        window.location.reload();
    } else {
        ad_delete_success(result, user_context);
    }
}


function comment_add(ad_id, text) {
    _call("AdComment", { "adId": ad_id, "text": text }, comment_add_success);
}

function comment_add_success(result) {
    var res = eval('(' + result + ')');

    var comment_add_button = document.getElementById('btn_send_comment_' + res.adId);
    var comment_text = document.getElementById('txtCommentText_' + res.adId);
    var remark_img = document.getElementById('remark_row_' + res.adId) ? document.getElementById('remark_row_' + res.adId) : (window.opener ? window.opener.document.getElementById('remark_gal_' + res.adId) : undefined);
    
    if (remark_img) {
        remark_img.setAttribute("_tooltip", comment_text ? comment_text.value.replace(/\n/g,'<br>') : 'רשום לעצמך הערה');
        remark_img.src = 'img/remark-'+ (res.isDeleted != 'False' ? 'off' : 'on') +'.gif' ;
    }    
    
    comment_add_button.value = res.isDeleted != 'False' ? 'שמור' : 'עדכן';
}

function reply_add(ad_id, text) {
    _call("AdReply", { "adId": ad_id, "text": text }, reply_add_success);
}

function reply_add_success(result) {
    var reply_title_row = document.getElementById('ad_reply_title_' + result);

    if (reply_title_row) {
        eval(reply_title_row.attributes["onclick"].value);
    }
}


function get_coords(c1, s1, h1, c2, s2, h2) {
    _call("GetCoords", { "City1": c1, "Street1": s1, "House1": h1, "City2": c2, "Street2": s2, "House2": h2 }, get_coords_success);
}

function get_coords_success(result) 
{
    var crds = eval('(' + result + ')');
    drawMap(crds.x1,crds.y1,crds.x2,crds.y2);
}

function UrlChange(Category) {


}

function tOnChangeMessages() {
    var Category = document.getElementById('c_ucBoards').value;

    var OldUrl = self.location.href;
    var StartSec = OldUrl.indexOf('sec=');
    var EndSec = OldUrl.indexOf('&a');
    var DeleteSaveParameter = OldUrl.substring(StartSec + 4, EndSec);

    var StartA = OldUrl.indexOf('&a=');
    var AParameter = OldUrl.substring(StartA);
    switch (Category) {
        case "רכב":
            location.replace('DeleteAndSaveManger.aspx?Categ=11&sec=' + DeleteSaveParameter + AParameter);
            break;
        case "נדל\"ן":
            location.replace('DeleteAndSaveManger.aspx?Categ=2&sec=' + DeleteSaveParameter + AParameter);
            break;
        case "יד שניה":
            location.replace('DeleteAndSaveManger.aspx?Categ=21&sec=' + DeleteSaveParameter + AParameter);
            break;
    } 
}


function RedirectToPrint(args) {
    switch (args) {
        case 'saved':
            location.replace('PrintAds.aspx?MessageType=saved');
            break;
        case 'deleted':
            location.replace('PrintAds.aspx?MessageType=deleted');
            break;
    }
}
function ChangeBoardState() {
    var Category = document.getElementById('c_ucBoards').value;
    switch (Category) {
        case "רכב":
                location.replace('EditSmartAgents.aspx?a=35&c=v');
            break;
        case "נדל\"ן":
                location.replace('EditSmartAgents.aspx?a=35&c=a');
            break;
        case "יד שניה":
                location.replace('EditSmartAgents.aspx?a=35&c=s');
            break;
    }
}

function callReload() {
    var oRedirect = new Redirect();
    var str_path = getQueryStringByKeyOrValue('c');
    oRedirect.RedirectFunc("EditSmartAgents.aspx?a=35&c=" + str_path, true, true, 2);
}
function DeleteAgent_Edit(agent_status, smart_agent_id) { 
   _call("UpdateSmartAgentStatus", { "Status": agent_status, "AgentId": smart_agent_id }, DeleteAgent_Edit_success);
}

function DeleteAgent_Edit_success() {
    HideLightBox('ucEditSmartAgents_ucDeleteAgent_LightBox');
    ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
    document.getElementById('spn_title_freeze').innerHTML = ' מחיקת סוכן ';
    callReload();
}

/*Update SmartAgent status*/
function UpdateAgentStatus(agent_status, smart_agent_id) {
     _call("UpdateSmartAgentStatus", { "Status": agent_status, "AgentId": smart_agent_id }, chanelocation_success);
}
function chanelocation_success() {
    document.getElementById('spn_title_freeze').innerHTML = ' מחיקת סוכן ';
    window.setTimeout("agent_success()", 10 * 10);
    HideLightBox('ucSmartAgentStep2_notesLightBox_LightBox');
    ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox',true);
    window.setTimeout("window.location.reload()", 1000 * 3);
}
function SuccessOnChange() {
   
}

function send_email(ad_id, targ_obj) {
    _call("SendEmail", { "adId": ad_id, "text": targ_obj.value }, reply_add_success);
    targ_obj.value = '';    
}


/* Animation Funcs */
function between(val, val_1, val_2) {
    if (val_1 < val_2)
        return (val_1 < val && val < val_2);
    else
        return (val_2 < val && val < val_1);

}

function Expander() {
    this.objId      = "";
    this.startValue = 0;
    this.endValue   = 0;
    this.velocity = 0;

    this.execute = function() {
        var s_obj = document.getElementById(this.objId).style;
        var obj_height = parseInt(s_obj.height);
        var _d = (this.startValue - this.endValue > 0) ? -1 : 1;

        if (obj_height)
            obj_height += (this.velocity * _d);
        else
            obj_height = this.startValue + (this.velocity * _d);

        if (between(obj_height, this.startValue, this.endValue)) {
            s_obj.height = obj_height + 'px';
            var o_this = this;
            setTimeout(function() { o_this.execute() }, 15);
        }
        else {
            s_obj.height = this.endValue + 'px';
            this.onComplete();
        }
    }

    this.onComplete = function() {}
}
function checkEmail(Email,error_text) {

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(Email.value)) 
    {
        Email.value = error_text;
        Email.style.color = "red";
        return false;
    }
    return true;
}
function checkEmpty(textbox,error_text) {
    if (textbox.value == "" || textbox.value == null || textbox.value == error_text) {
        textbox.style.color = "red";
        textbox.value = error_text;
        return false;
    }
    else
        return true;
}
function SendMail(PostId) {
    var i = 0;

    var v = document.getElementById("SendToFriend_PostId");
    PostId = v.getAttribute("value");

    var SearchType = document.getElementById("SendToFriend_SearchType");
    SearchType = SearchType.getAttribute("value");
    var RecipientName = document.getElementById('TextBoxRecipientName');
    var RecipientAdress = document.getElementById('TextBoxRecipientAdress');
    var SenderName = document.getElementById('TextBoxSenderName');
    var SenderAdress = document.getElementById('TextBoxSenderAdress');
    var TitleMessage = document.getElementById('TextBoxTitleMessage');
    
    if (!checkEmpty(RecipientName,'אנא הזן שם הנמען')) {
        RecipientName.onfocus = function() { ErrorClick(RecipientName) };
        i = 1;
    }

    if (!checkEmpty(RecipientAdress, 'אנא הזן מייל הנמען')) {
        RecipientAdress.onfocus = function() { ErrorClick(RecipientAdress) };
        i = 1;
    }else if (!checkEmail(RecipientAdress, 'כתובת מייל אינה חוקית')) {
        RecipientAdress.onfocus = function() { ErrorClick(RecipientAdress) };
        i = 1;
    }
    
    if (!checkEmpty(SenderName, 'אנא הזן שם השולח')) {
        SenderName.onfocus = function() { ErrorClick(SenderName) };
        i = 1;
    }
    
    if (!checkEmpty(SenderAdress, 'אנא הזן מייל השולח')) {
        SenderAdress.onfocus = function() { ErrorClick(SenderAdress) };
        i = 1;
    }else if (!checkEmail(SenderAdress, 'כתובת מייל אינה חוקית')) {
        SenderAdress.onfocus = function() { ErrorClick(SenderAdress) };
        i = 1;
    }
    
    if(i == 1)
        return false;

    _call("SendMail", { "_PostId": PostId, "SearchType": SearchType, "to": RecipientAdress.value, "from": SenderAdress.value, "SenderName": SenderName.value, "ReciverName": RecipientName.value, "subject": RecipientName.value + " שלח לך הודעה מאתר זה וזה", "body": TitleMessage.value }, SendMail_Succeded);
    ClearSendToFriend();
    var vLightBoxId = document.getElementById("SendToFriend_LiteBoxId").getAttribute("value");
    HideLightBox(vLightBoxId);
    ShowLightBox('SR_LightBox_SendEmailSucceded_LightBox', true);
    ShowLightBox('LightBox_SendEmailSucceded_LightBox', true);
    
    //setTimeout("HideLightBox('SR_LightBox_SendEmailSucceded_LightBox');", 1500);
}


function SendContactUs(Subject, FName, LName, Company,  Email, Message) {
    //alert(Subject + " " + FName + " " + LName + " " + Email + " " + Message);
    _call("SaveCRMContactUs", { "Subject": Subject, "FName": FName, "LName": LName, "Email": Email, "Message": Message }, Send_SuccessContactUs);
    
}

function SendMail_Succeded() {
}

function ClearSendToFriend() {

    document.getElementById('TextBoxRecipientName').value = "";
    document.getElementById('TextBoxRecipientAdress').value = "";
    document.getElementById('TextBoxSenderName').value = "";
    document.getElementById('TextBoxSenderAdress').value = "";
    document.getElementById('TextBoxTitleMessage').value = "";
}
function ErrorClick(Email) {
    Email.value = "";
    Email.style.color = "black";    
    Email.onfocus = function() { };    
}
function HurtfulContens(PostId) {
    var i = 0;
    var v = document.getElementById("SendToFriend_PostId");
    PostId = v.getAttribute("value");
    var FirstName = document.getElementById('TextBoxCName');
    var Email = document.getElementById('TextBoxCEmail');
    var Message = document.getElementById('TextBoxHurtfulDescription');

    if (!checkEmpty(Message, 'אנא הזן את תאור הפגיעה')) {
        Message.onfocus = function() { ErrorClick(Message) };
        i = 1;
    }

    if (!checkEmpty(Email, 'אנא הזן את כתובת האימייל')) {
        Email.onfocus = function() { ErrorClick(Email) };
        i = 1;
    }else if (!checkEmail(Email,'כתובת מייל אינה חוקית')) {
        Email.onfocus = function() { ErrorClick(Email) };
        i = 1;
    }
    
    if (i == 1)
        return false;

    _call("HurtfulContens", { "AdId": PostId.split('_')[1], "FirstName": FirstName.value, "Email": Email.value, "Message": Message.value }, HurtfulContens_Succeded);

    FirstName.setAttribute("value", "''");
    Email.setAttribute("value", "''");
    Message.setAttribute("value", "''");

    var vLightBoxId = document.getElementById("SendToFriend_LiteBoxId").getAttribute("value");
    HideLightBox(vLightBoxId);
    ShowLightBox('SR_LightBox_HurtfulContensSucceded_LightBox',true);
    //setTimeout("HideLightBox('SR_LightBox_HurtfulContensSucceded_LightBox');", 1500);
}

function HurtfulContens_Succeded() {
}

function ClearHurtfulContens() {

    document.getElementById('TextBoxCName').value = "";
    document.getElementById('TextBoxCEmail').value = "";
    document.getElementById('TextBoxHurtfulDescription').value = "";
}
 
function Fader() {
    this.obj;
    this.startValue = 0;
    this.endValue = 0;
    this.velocity = 0;

    var opacity;
    this.execute = function() {
        var s_obj;
       
        if (this.obj.style || this.obj.pop) {
            s_obj = this.obj;
        } else {
            s_obj = document.getElementById(this.obj);
        }

        var _d = (this.startValue - this.endValue > 0) ? -1 : 1;

        if (opacity)
            opacity += (this.velocity * _d);
        else
            opacity = this.startValue + (this.velocity * _d);
        //alert(opacity);
        if (between(opacity, this.startValue, this.endValue)) {
            if (s_obj[0])
                for (var i = 0; i < this.obj.length; i++)
                setOpacity(s_obj[i], opacity);
            else
                setOpacity(s_obj, opacity);

            var o_this = this;
            setTimeout(function() { o_this.execute() }, 15);
        }
        else {
            if (s_obj[0])
                for (var i = 0; i < this.obj.length; i++)
                setOpacity(s_obj[i], opacity);
            else
                setOpacity(s_obj, opacity);
            this.onComplete();
        }
    }

    this.onComplete = function() { }
}


function MakeFavorite() {
    if (window.sidebar) {
        window.sidebar.addPanel('זה וזה','http://www.zvz.co.il','');
    }
    else if (window.external) {
        window.external.AddFavorite('http://www.zvz.co.il', 'זה וזה');
    }    
}

/*SearchResult Call to Refresh Controls*/
function LoadCategoryType() {
    var query = window.location.search.substring(1);
    var pairs = query.split("&");
    var value = "";
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        value = pairs[i].substring(pos + 1);
    }
    return ChangeCategory(parseInt(value));
    //ReloadControlSM(ChangeCategory(parseInt(value)));
}
function ChangeCategory(category) {
    var retValue;
    switch (category) {
        case 1: retValue = 'Appartment'; break;
        case 2: retValue = "Appartment"; break;
        case 3: retValue = "Appartment"; break;
        case 5: retValue = "Appartment"; break;
        case 6: retValue = "Appartment"; break;
        case 11: retValue = 'Vehicles'; break;
        case 12: retValue = "Vehicles"; break;
        case 13: retValue = "Vehicles"; break;
        case 14: retValue = "Vehicles"; break;
        case 21: retValue = "SecondHand"; break;
    }
    return retValue;
}

function _click(obj_id) {
    var obj = document.getElementById(obj_id);

    if (obj.click) {
        obj.click();
    }else if (obj.attributes["onclick"]) {
                eval(obj.attributes["onclick"].value);
    }

    return;
}

function appendInnerScript(obj_id) {
    var obj = document.getElementById(obj_id);
    var script = obj.getElementsByTagName("script")[0];
   
    if (script) {
        var elm_script = document.createElement('script');
        if (elm_script.canHaveChildren == null || elm_script.canHaveChildren) {
            elm_script.appendChild(document.createTextNode(script.innerHTML));
        } else {
            elm_script.text = script.innerHTML;
        }

        obj.appendChild(elm_script);
    }
}

function executeInnerScript(obj) {
    var script = obj.getElementsByTagName("script")[0];
    if (script) {
            eval(script.innerHTML);
    }
}

function switchInputs(inp1, inp2, check_empty_inp) {
    var obj_inp1 = document.getElementById(inp1);
    var obj_inp2 = document.getElementById(inp2);

    if ((check_empty_inp && obj_inp2.value.length == 0) || !check_empty_inp) {
        obj_inp1.style.display = '';
        obj_inp2.style.display = 'none';
        if (!check_empty_inp)
            obj_inp1.focus();
    }
}

function switchInputText(inp, text, check_empty_inp) {
    var obj_inp = document.getElementById(inp);
    
    if ((check_empty_inp && obj_inp.value.length == 0) || !check_empty_inp) {
        obj_inp.value = text;
    }
}
function ClearInputsByName(ElementId, DoEval, ElementName) {
    ClearInputs(ElementId, DoEval);
    ClearInputs(ElementId, DoEval, ElementName);
}
function ClearInputs(ElementId, DoEval, ElementName) {
    var v = document.getElementById(ElementId);
    var Elements;
    if(ElementName == null)
        Elements = v.getElementsByTagName("Input");
    else
        Elements = v.getElementsByTagName(ElementName);

    for (var i = 0; i < Elements.length; i++) {
        if (Elements[i].name != "" && (Elements[i].type == "text") || (Elements[i].nodeName.toLowerCase() == "textarea")) {
            Elements[i].value = "";
            if ((DoEval) || (DoEval == null)) {
                if (Elements[i].attributes["onblur"] != null) {
                    eval(Elements[i].attributes["onblur"].value);
                } 
            }
        }
    }

    /*Clean Textarea*/
    Elements = v.getElementsByTagName("TEXTAREA");
    
    if (Elements[0])
        if (Elements[0] != null)
            Elements[0].value = '';
}

function getSelectedValue() {
    var chk = $get('chkFreeze1');
   
    if(chk != null){
       return chk.checked;
    }
}

function get_Days() {
    //var selectedValue = document.getElementById('ucSmartAgentStep2_freezeAgent_freeAgent_ddlDays').value;
    var selectedValueDays = document.getElementById('days');
    var value;

    if (selectedValueDays) {
        value = document.getElementById('days').value;
        var date = new Date();
        
        if (value == 'יום') {
            return value = date.getDate();
        }
        else {
            return value;
        }
    }
    
}

function get_Months() {
    //var selectedValue = document.getElementById('ucSmartAgentStep2_freezeAgent_freeAgent_ddlMonths').value;

    var selectedValueMonths = document.getElementById('months');
    var value;

    if (selectedValueMonths) {
        var date = new Date();
        value = document.getElementById('months').value;
        if (value == 'חודש') {
            return value = date.getMonth() + 1;
        }
        else {
            return value;
        }
    }
}
function get_Years() {
    //var selectedValue = document.getElementById('ucSmartAgentStep2_freezeAgent_freeAgent_ddlYears').value;
    var selectedValueYears = document.getElementById('years');
    var value;

    if (selectedValueYears) {
        var date = new Date();
        value = document.getElementById('years').value;
        if (value == 0) {
            return value = date.getFullYear();
        }
        else {
            return value;
        }
    }
}

function update_Scan(AgentId, LightBoxId) {
    var IsTotalFreeze = getSelectedValue();
    var ddlYears = $get('years');
     
    if (IsTotalFreeze == true) {
        
        UpdateAgentStatus(1, AgentId);
        agent_success();
    }
    else {//if(IsTotalFreeze == true && get_Years().toString() != ''){
        
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth() + 1;
        var year = date.getFullYear(); 

        if (get_Days() <= day && get_Months() <= month && get_Years() <= year) {
            var div_obj = document.getElementById('errorMessage');
            div_obj.style.display = 'block';

            if (typeof event != "undefined")
            {
                window.event.returnValue = false;
            }
            else 
            {
                return false;
            }

        } else {
            update_scandate(get_Days(), get_Months(), get_Years(), AgentId);
        }
    }
}

function update_scandate(Days, Months, Years, AgentId) {
    _call("FreezeAgents", { "Days": Days, "Months": Months, "Years": Years, "AgentId": AgentId }, agent_success);
}
/**************************************  Edit Agent Functions  **************************************************/
function getPhoneEdit() {
    var txt_box2 = document.getElementById('s_Phone_Obj').value;
    var txt_box1 = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone').value;
    var phoneNumber = txt_box2 + txt_box1;
    return phoneNumber;
}

function SendSmsEdit(PhoneNumber) {
    var regx = new RegExp("\\d{7}");
    var chk_box_IAlowSendSms = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var txt_box = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');
    var isValidToSend = false;

    if (chk_box_IAlowSendSms.checked && txt_box.value.length > 1) {
        if (regx.test(txt_box.value)) {
            isValidToSend = true;
        }
        else
            isValidToSend = false;
    }
    else
        isValidToSend = false;

    if (isValidToSend == false) {
        document.getElementById('ucEditSmartAgents_agentEdit_CustomValidator2').innerHTML = '';
        document.getElementById('showPhoneError').style.display = 'block';
        document.getElementById('showPhoneError').innerHTML = "נא למלא  מס' טל'";
        document.getElementById('ucEditSmartAgents_agentEdit_IAlow').checked = false;
    }
    
    if (isValidToSend) {
        document.getElementById('showPhoneError').style.display = 'none';
        document.getElementById('showPhoneError').innerHTML = "";
        ShowLightBox('ucEditSmartAgents_agentEdit_ucLightBoxSms_LightBox', false);
        _call("SendSmsForValidation", { "PhoneNumber": PhoneNumber }, SendSms_SuccessEdit);
    }
}

function changeLightBoxTitleEdit(title_id, text) {
    document.getElementById(title_id).innerHTML = text;
}

function SendSms_SuccessEdit() {

    var pwd = document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_codeText');
    var valueToCheck = document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_hidden1').value;
  
    var cookie = getCookie('SmsPassword');
    var validator = document.getElementById('errorDivSms');
    
    valueToCheck = cookie.replace("SmsPassword=", "");
    var counter = 0;
    if (pwd) {
        if (valueToCheck == pwd.value && pwd.value.length > 1) {
            HideLightBox('ucEditSmartAgents_agentEdit_ucLightBoxSms_LightBox');
            changeLightBoxTitleEdit('spn_title_freeze', 'אישור סיסמה');
            ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
            validator.style.display = 'none';

            return true;
        }
        else {
            var div_obj = document.getElementById('error');
            var successValue = document.getElementById('successValue');
            var btn_obj = document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_btnSaveData');

            if (pwd.value.length > 1) {
                div_obj.innerHTML = "סיסמה שגויה, נסה שנית";
                successValue.value += 1;

                if (successValue.value.length == 2) {
                    var ahref = document.createElement('a');
                    var text = document.createTextNode('צור קשר');
                    ahref.style.color = "blue";
                    ahref.href = "javascript:HideLightBox('ucEditSmartAgents_agentEdit_ucLightBoxSms_LightBox');ShowLightBox('ucLoginBarRegistred_ucLight_LightBox', false)";
                    div_obj.innerHTML = ' ' + 'לעזרה ביצירת סוכן חכם' + ' ';
                    ahref.appendChild(text);
                    div_obj.appendChild(ahref);
                    successValue.value = '';

                    btn_obj.click = function() {
                        return false;
                    }
                }
            }
            return false;
        }
    }
}
function checkWhatToRunEdit() {
    RemoveCheckBox1();
    return firstCheckIfUserCheckCellEdit();
}
function firstCheckIfUserCheckCellEdit() {
    var cellChkBox = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var cellMainChkBox = document.getElementById('ucEditSmartAgents_agentEdit_IAlow');
    var successValue = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');
    var validator = document.getElementById('errorDivSms');
    var phone_validtor = document.getElementById('ucEditSmartAgents_agentEdit_CustomValidator2');

    if (cellChkBox.checked && cellMainChkBox.checked && successValue.value.length >= 7) {
        changeLightBoxTitleEdit('spn_title_freeze', 'עידכון סוכן');
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
        document.getElementById('spn').innerHTML = 'הפעולה בוצעה בהצלחה!';
        return true;
    }
    else if (cellChkBox.checked && cellMainChkBox.checked && successValue.value.length <= 6) {
        cellMainChkBox.checked = false;
        phone_validtor.style.display = 'block';
        return false; 
    }
    else if (!cellChkBox.checked && !cellMainChkBox.checked && successValue.value.length < 1) {
        validator.style.display = 'none';
        changeLightBoxTitleEdit('spn_title_freeze', 'עידכון סוכן')
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
        document.getElementById('spn').innerHTML = 'הפעולה בוצעה בהצלחה!';
        return true;
    }
    else if (cellChkBox.checked && !cellMainChkBox.checked && successValue.value.length <= 6) {
        cellMainChkBox.checked = false;
        phone_validtor.style.display = 'block';
        return false;
    }
    else {
        validator.style.display = 'block';       
        return false;
    }

}

function validateCheckBox() {
    var obj_chk = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendEmail');
    var btn_val = document.getElementById('ucEditSmartAgents_agentEdit_btnUpdateAgent');
    var err1 = document.getElementById('errorDiv1');
    var isValid = false;

    if (!obj_chk.checked) {
        btn_val.onclick = function() {
            err1.innerHTML = "אנא סמן בשביל להמשיך";
            return false;
        }
    }
    else {
        btn_val.onclick = function() {
            err1.innerHTML = "";
            return true;
        }
    }

    return isValid;
}

function ClearName(obj) {
    if (obj != null) {
        if (obj.value == 'בחר שם לסוכן') {
            obj.value = '';
        }
    }
}

function ReturnName(obj) {
    if (obj != null) {
        if (obj.value != '') {
            obj.value = obj.value;
        }
        else {
            obj.value = 'בחר שם לסוכן';
        }
    }
}
//*********************************
//Get Values into the hidden
//
function getDataIntoHidden() {
    var ddl_phone = document.getElementById('s_Phone_Obj');
    var hdn_value = document.getElementById('ucEditSmartAgents_agentEdit_hdnPhone');
    if (ddl_phone) {
        hdn_value.value = ddl_phone.value;
    }
    var valuesString = ParseStringIntoXML(hdn_value.value);
    hdn_value.value = valuesString;
    //alert(hdn_value.value);
}

function ParseStringIntoXML(phone) {
    var full_phone = phone + document.getElementById('ucEditSmartAgents_agentEdit_txtPhone').value;
    var retValue = new Array();
    retValue.push(full_phone);
    return retValue;
}

function InsertParsedValuesIntoDropDowns(phone) {
    var ddl_phone = document.getElementById('s_Phone_Obj');
    if (ddl_phone) {
        ddl_phone.value = phone;
    }
}


function getCorrectValues() {
    var obj_chk = document.getElementById('ucEditSmartAgents_agentEdit_IAlow');
    var obj_chk2 = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var txt_box = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone').value;
    var innerPswCheck = document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_codeText').value;
    if (obj_chk.checked == true && obj_chk2.checked == true && txt_box.length > 1 && innerPswCheck.length == 4)
        return true;
    else
        return false;
}

function RemoveCheckBox1() {
   
    var ialow = document.getElementById('ucEditSmartAgents_agentEdit_IAlow');
    var ialowsms = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var text = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');
    var validatorDiv = document.getElementById('showPhoneError');
    var validatorSpn = document.getElementById('ucEditSmartAgents_agentEdit_CustomValidator2');
    var validatorDiv2 = document.getElementById('errorDivSms');

    if (!ialowsms.checked && !ialow.checked || (ialowsms.checked && !ialow.checked)) {
        validatorDiv.style.display = 'none';
        validatorSpn.style.display = 'none';
        ialow.checked = false;
    }

    if (!ialowsms.checked && text.value.length >= 7) {
        validatorSpn.innerHTML = 'סמן בשביל להמשיך';
        validatorDiv2.style.display = 'none';
        ialow.checked = false;
    }
    if (text.value.length > 1 && ialowsms.checked) {
        validatorDiv.style.display = 'none';
        validatorSpn.style.display = 'none';
    }

    if (text.value.length >= 7 && ialowsms.checked && !ialow.checked) {
        validatorSpn.style.display = 'none';
    }

    if (text.value.length >= 7 && (!ialowsms.checked && !ialow.checked)) {
        validatorSpn.style.display = 'block';
    }

    if (ialowsms.checked && text.value.length <= 1 && ValidateCell()) {
        validatorDiv.style.display = 'block';
    }
    if (ialow.checked && ialowsms.checked && text.value.length >= 7) {
        validatorDiv.style.display = 'none';
        validatorSpn.style.display = 'none';
    }
    if (!ialow.checked && !ialowsms.checked && text.value.length < 1) {
        validatorDiv.style.display = 'none';
        validatorSpn.style.display = 'none';
    }
}
/*Is Agent valid to save*/
function ValidateChanges() {
    var array_validation = new Array();
    var validtion = false;
    var obj_btn = document.getElementById('ucStep1_btnSave');
    var chk_ialow = document.getElementById('ucStep1_IAlow');
    var isValid = false;
   
    switch (getQueryStringByKeyOrValue('qsCateg')) {
        case "secondhand":
            array_validation[0] = document.getElementById('s_yad2_Category').value;
            //alert(array_validation[0]);
            array_validation[1] = document.getElementById('s_yad2_Product').value;
            array_validation[2] = document.getElementById('s_yad2_PriceNIS').value;
            array_validation[3] = document.getElementById('s_yad2_MainRegion').value;
            array_validation[4] = document.getElementById('s_free_Text').value;
            break;
        case "appartment":
             array_validation[0] = document.getElementById('s_app_Region').value;
             array_validation[1] = document.getElementById('s_app_PropertyTypeIndex').value;
             array_validation[2] = document.getElementById('s_app_Floor').value;
             array_validation[3] = document.getElementById('s_app_Rooms').value;
             array_validation[4] = document.getElementById('s_app_PriceNIS').value;
             array_validation[5] =  document.getElementById('s_app_FreeText').value;
            break;
        case "vehicles":
            array_validation[0] = document.getElementById('s_car_Maker').value;
            array_validation[1] = document.getElementById('s_car_Model').value;
            array_validation[2] = document.getElementById('s_car_Year').value;
            array_validation[3] = document.getElementById('s_car_PriceNIS').value;
            array_validation[4] = document.getElementById('s_car_gear').value;
            array_validation[5] = document.getElementById('s_car_Hand').value;
            array_validation[6] = document.getElementById('s_car_MainRegion').value;
            array_validation[7] = document.getElementById('s_free_Text').value;
            break;
    }

    for (var i = 0; i < array_validation.length; i++) {

        if (array_validation[i] != '') {
            validtion = true;
            break;
        }
        else {
            validtion = false;
        }
    }
    
    if (!validtion) {
        document.getElementById('spn_title_freeze').innerHTML = "אזהרה";
        document.getElementById('spn').innerHTML = "אנא בצע חיפוש אחד לפחות";
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true)

        obj_btn.onclick = function() {
            if (validate_phone())
                chk_ialow.checked = true;
            else
                chk_ialow.checked = false;

            if (obj_btn.addEventListener)
                obj_btn.addEventListener('click', ValidateChanges, false);
            else
                obj_btn.attachEvent('onclick', ValidateChanges, false);
            return false;
        }
        isValid = false;
    }
    else {
        obj_btn.onclick = function() {
            if (document.getElementById('ucStep1_IAlowSendSms').checked && document.getElementById('ucStep1_IAlow').checked) {
                document.getElementById('ucStep1_CustomValidator2').value = '';
                document.getElementById('errorDivSms').value = '';
            }
            if (obj_btn.addEventListener)
                obj_btn.addEventListener('click', ValidateChanges, false);
            else
                obj_btn.attachEvent('onclick', ValidateChanges, false);
            return true;
        }
        isValid = true;
    }
    return isValid;
}

function validate_phone() {
    var valid = false;
    var pre_phone = document.getElementById('s_Phone_Obj').value;
    var rest_phn = document.getElementById('ucStep1_txtPhone').value;
    var chk_ialow = document.getElementById('ucStep1_IAlow');
    var chk_sms = document.getElementById('ucStep1_IAlowSendSms');
    var validatorSpn = document.getElementById('ucStep1_CustomValidator2');
    var validatorDiv = document.getElementById('showPhoneError');
    var user_phone = new Array();
    user_phone = document.getElementById('ucStep1_hdnAgentName').value.split(',');
    var full_phone = pre_phone + rest_phn;

    if (full_phone.length > 3) {
        for (var i = 0; i < user_phone.length - 1; i++) {
            var found = user_phone[i].search(full_phone);
            if (found == -1) {
                chk_ialow.checked = false;
                valid = false;
                validatorDiv.style.display = 'none';
                continue;
            }
            else if (found == 0) {
                chk_ialow.checked = true;
                if (!chk_sms.checked)
                    chk_sms.checked = true;
                valid = true;
                break;
            }
        }
    }
    else {
        if (chk_sms.checked) {
            validatorDiv.innerHTML = "נא למלא  מס' טל'";
            validatorDiv.style.display = 'block';
        }
        chk_ialow.checked = false;
    }
    return valid;
}

function clearSmsObjectEdit(ToClear) {

    var cellTextBox = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');
    var cellChkBox = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var cellMainChkBox = document.getElementById('ucEditSmartAgents_agentEdit_IAlow');
    var div_obj = document.getElementById('error');
    var successValue = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');

    if (ToClear) {
        if (div_obj != null) {
            div_obj.innerHTML = '';
            successValue.value = '';
            cellMainChkBox.checked = false;
            cellChkBox.checked = true;
            //cellTextBox.value = '';
        }
    }
}

/********************************************************************************************************************/

function getPhone() {
    var txt_box2 = document.getElementById('s_Phone_Obj').value;
    var txt_box1 = document.getElementById('ucStep1_txtPhone').value;
    var phoneNumber = txt_box2 + txt_box1;
    return phoneNumber;
}

function SendSms(PhoneNumber) {
}

function ValidateCode(PhoneNumber,Code) {
    _call("ValidateCode", { "Phone": PhoneNumber, "Code": Code }, ValidateCode_Success);
}

function ValidateCode_Success(result) {
    if (result) {
        HideLightBox('ucStep1_ucLightBoxSms_LightBox');
        HideLightBox('ucEditSmartAgents_agentEdit_ucLightBoxSms_LightBox');
        document.getElementById('cvalSMS_isvalid').value = 1;
        try {
            document.getElementById('ucStep1_btnSave').click();
        } catch (ex) {
            document.getElementById('ucEditSmartAgents_agentEdit_btnUpdateAgent').click();
        }

    } else {
        var err = document.getElementById('error');
        err.style.visibility = 'visible';
    }
}

function ValidateEmailDomain(Email,success_func) {
    _call("ValidateEmailDomain", { "Email": Email }, success_func ? success_func : ValidateEmailDomain_Success);
}

function ValidateEmailDomain_Success(result) {
    alert(result);
}



function changeLightBoxTitle(title_id, text) {
    document.getElementById(title_id).innerHTML = text;
}
function SendSms_Success(code) {
    var pwd = document.getElementById('ucStep1_ucLightBoxSms_ctl01_codeText').value;
    //var valueToCheck = document.getElementById('ucStep1_ucLightBoxSms_ctl01_hidden1').value;
    var cookie = getCookie('SmsPassword');
    var validator = document.getElementById('errorDivSms');
    var valueToCheck = code; //cookie.replace("SmsPassword=", "");
    var counter = 0;

    if (valueToCheck == pwd && pwd.length > 1) {
        HideLightBox('ucStep1_ucLightBoxSms_LightBox');
        changeLightBoxTitle('spn_title_freeze', 'אישור סיסמה');
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
        validator.style.display = 'none';
        return true;
    }
    else {
        var div_obj = document.getElementById('error');
        var successValue = document.getElementById('successValue');
        var btn_obj = document.getElementById('ucStep1_ucLightBoxSms_ctl01_btnSaveData');

        if (pwd.length > 1) {
            div_obj.innerHTML = "סיסמה שגויה, נסה שנית";
            successValue.value += 1;
            
            if (successValue.value.length == 2) {
                var ahref = document.createElement('a');
                var text = document.createTextNode('צור קשר');
                ahref.style.color = "blue";
                ahref.href = "javascript:HideLightBox('ucStep1_ucLightBoxSms_LightBox');ShowLightBox('ucLoginBarRegistred_ucLight_LightBox', false)";
                div_obj.innerHTML = ' ' + 'לעזרה ביצירת סוכן חכם' + ' ';
                ahref.appendChild(text);
                div_obj.appendChild(ahref);
                successValue.value = '';
                
                btn_obj.click = function() {
                    return false;
                }
            }
            
        }
        return false;
    }
}
function checkWhatToRun() {
    validate_phone();
    ValidateChanges();
   return firstCheckIfUserCheckCell();
}
function firstCheckIfUserCheckCell() {
    var cellChkBox = document.getElementById('ucStep1_IAlowSendSms');
    var cellMainChkBox = document.getElementById('ucStep1_IAlow');
    var successValue = document.getElementById('ucStep1_ucLightBoxSms_ctl01_codeText');
    var validator = document.getElementById('errorDivSms');
    var phone_validator = document.getElementById('showPhoneError');

    if (cellChkBox.checked && cellMainChkBox.checked) {
        return true;
    }
    else if (!cellChkBox.checked && !cellMainChkBox.checked && successValue.value.length < 1) {
        validator.style.display = 'none';
        return true;
    }
    else {
        if (document.getElementById('ucStep1_txtPhone').value == '') {
            phone_validator.style.display = 'block';
            phone_validator.innerHTML = "נא למלא  מס' טל'";
        }
        else {
            phone_validator.style.display = 'none';
            phone_validator.innerHTML = '';
        }
        validator.style.display = 'block';
        return false;
    }
}
function clearSmsObject(ToClear) {

    var cellTextBox = document.getElementById('ucStep1_txtPhone');
    var cellChkBox = document.getElementById('ucStep1_IAlowSendSms');
    var cellMainChkBox = document.getElementById('ucStep1_IAlow');
    var div_obj = document.getElementById('error');
    var successValue = document.getElementById('ucStep1_ucLightBoxSms_ctl01_codeText');
    if (!successValue) successValue = document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_codeText');
   
    if (ToClear) {
        if (div_obj != null) {
            div_obj.innerHTML = '';
            successValue.value = '';
            cellMainChkBox.checked = false;
            cellChkBox.checked = true;
            //cellTextBox.value = '';
        }
    }
}

function getQueryString() {
    var query = window.location.search.substring(1);
    var pairs = query.split("&");
    var value = "";
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        value = pairs[i].substring(pos + 1);
    }
    return value;
}

function getQueryStringByKeyOrValue(get_value) {
    var query = window.location.search.substring(1);
    var pairs = query.split("&");
    var arr_kvp = [];
    var returnValue = '';
    for (var i = 0; i < pairs.length; i++) {
        var position = pairs[i].indexOf('=');
        if (position == -1) continue;
        arr_kvp[pairs[i].substring(0, position)] = pairs[i].substring(position + 1);
    }
    for (var i = 0; i < pairs.length; i++) {
        returnValue = arr_kvp[get_value];
        break;
    }
    return returnValue;
}

function agent_success(HideLightBoxID, ShowLightBoxID, BackTo) {
    var dialog = $find('ucSmartAgentStep2_freezeAgent1_LightBox');
    var day;
    var month;
    var years;
    var date;


    if (document.getElementById('days') != null)
        day = document.getElementById('days').value;
    if (document.getElementById('months') != null)
        month = document.getElementById('months').value;
    if (document.getElementById('years') != null)
        years = document.getElementById('years').value;

    if (day != undefined) {
        date = day + '/';
    }

    if (month != undefined) {
        date += month + '/';
    }

    if (years != undefined) {
        date += years;
    }
   
    if (date != undefined || date != null) {
        document.getElementById('spn').innerHTML = '';
        document.getElementById('dateNote').innerHTML = 'מוקפא עד לתאריך:' + '  ' + date.toString();
        setTimeout("ShowLightBox('ucSmartAgentStep2_freezeAgent1_LightBox', true)", 1000 * 1);
        var redirectString = new String();  
        redirectString = 'SmartAgent2.aspx?a=35&qsCateg=' + getQueryString();
        window.setTimeout("location.replace('"+redirectString +"')", 1000 * 2);
    }
    if (getSelectedValue()) {
        document.getElementById('spn').innerHTML = '';
        document.getElementById('dateNote').innerHTML = '         מוקפא עד להודעה חדשה';

        
        
        HideLightBox('ucSmartAgentStep2_freezeAgent_LightBox');
        //ShowLightBox('ucSmartAgentStep2_freezeAgent1_LightBox', true);

    } else {

        
        HideLightBox('ucSmartAgentStep2_notesLightBox_LightBox');
        HideLightBox(HideLightBoxID);
        HideLightBox('ucSmartAgentStep2_freezeAgent_LightBox');
        ShowLightBox('ucSmartAgentStep2_freezeAgent1_LightBox', true);

        ShowLightBox(ShowLightBoxID, true);
        
        if(BackTo == null)
            window.setTimeout("location.replace('EditSmartAgents.aspx?a=35')", 1000 * 2);
        else
            window.setTimeout("location.replace('" + BackTo + " ')", 1000 * 2);
            
    }
}

function freezeAgent(AgentId, _Date) {

    var isValid = false;
    var dateTime = new Date();
    var radNoDate = document.getElementById('ucEditSmartAgents_radFreezeNoDate');
    var title_spn = document.getElementById('spn_title_freeze'); title_spn.innerHTML = 'הקפאת סוכן חכם';
    var content_spn = document.getElementById('spn'); content_spn.innerHTML = 'הפעולה בוצעה בהצלחה';
    //get's object if user choose no date fixed
    //freeze than it's check's if radio button not checked
    //than it's false else it's true
    var curr_date = dateTime.getDate() + '/' + (dateTime.getMonth() + 1) + '/' + dateTime.getFullYear();
    
    var arr_date = new Array();
    arr_date = _Date.split('/');
    
    var day = arr_date[0];
    var month = arr_date[1];
    var year = arr_date[2];
    
    //handles dates if the date to be sent to db
    //is bigger that current date than true
    //else if equals or less than throw exception
    //into div error if (!radNoDate.checked) {
    
    //if checkbox of no date not checked
    if (!radNoDate.checked) {
        //if year equals or bigger than requested
        if ((parseInt(year) < dateTime.getFullYear()) || (dateTime.getFullYear() == parseInt(year))) {
            //if month is equals or bigger than requested
            if (parseInt(month) <= (dateTime.getMonth() + 1)) {
                if (parseInt(day) < dateTime.getDate() || parseInt(day) == dateTime.getDate()) {
                    isValid = false;
                }
                else if (parseInt(month) >= (dateTime.getMonth() + 1)) {
                    isValid = true;
                }
            } 
        }
    }

    //if radio no date checked than isValid
    if (radNoDate.checked == true) {
        isValid = true;
    }
    
    if (isValid) {
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
        _call("FreezeAgents", { "AgentId": AgentId, "Date": _Date }, ShowFrozenMessage);
    }
    else {
        isValid = false;
    }
    return isValid;
}

function UnFreeze() {
    var radBox = document.getElementById('ucEditSmartAgents_UnFreeze');
    var vld_elem = document.getElementById('dateError');
    var btn = document.getElementById('ucEditSmartAgents_btnFreeze');
    var divbtn = document.getElementById('btn');
    btn.href = "javascript:void(0);";

    if (radBox.checked) {
        
        document.getElementById('spn_title_freeze').innerHTML = 'הפשרת סוכן חכם';
        document.getElementById('spn').innerHTML = 'הפעולה בוצעה בהצלחה';
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
        _call("UpdateSmartAgentStatus", { "Status": 99, "AgentId": getQueryString() });
        window.setTimeout("location.replace(window.location.search.substring(0))", 1000 * 3);
    }
    else {
        freezeAgentWithValidation();
    }
}


function FreezeAgent(agent_status, smart_agent_id) {
    _call("UpdateSmartAgentStatus", { "Status": agent_status, "AgentId": smart_agent_id }, FreezeAgent_success);
}

function FreezeAgent_success() {
    var content_spn = document.getElementById('spn');
    document.getElementById('spn_title_freeze').innerHTML = ' הפשרת סוכן חכם ';
    content_spn.innerHTML = 'הפעולה בוצעה בהצלחה';
    ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
    window.setTimeout("location.replace(window.location.search.substring(0))", 1000 * 2);
}


function ShowFrozenMessage() {
    //ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', true);
    window.setTimeout("window.location.reload(true)", 1000 * 3);
}
function chkToggleAll(checked, name) {
    var objs = document.getElementsByName(name);

    for (var i = 0; i < objs.length; i++) {
        try{
            objs[i].checked = checked;
        }catch(ex){}
    }
}

//Simlified Collapsible Panel Extender To Replace ACT's buggy one

function CollapsiblePanel() {
    this.CollapsedPanelId= "";
    this.Height = 100;
    this.Velocity = 50;
    this.Elements = new Array();
    this.OpenByDefault = false;
    this.IsOpen = function() {
        var obj_panel = document.getElementById(this.CollapsedPanelId);
        return (obj_panel && obj_panel.style.display != 'none');
    };
    this.Init = function() {

        var elm;
        for (var i = 0; i < this.Elements.length; i = i + 3) {
            elm = document.getElementById(this.Elements[i]);

            if (elm) {
                elm._elements = this.Elements;
                elm._panel = this.CollapsedPanelId;
                elm._height = this.Height;
                elm._veloc = this.Velocity;
                elm._pre = this.PreToggle;
                elm.onclick = this.Toggle;

                if (elm.addEventListener) {
                    elm.addEventListener('onclick', this.Toggle, false);
                }
                else if (elm.attachEvent) {
                    elm.attachEvent('click', this.Toggle);
                }

                //if (elm.captureEvents) elm.captureEvents(Event.CLICK);
            }
        }
        if (elm && this.OpenByDefault) {
            if (elm.click) {
                elm.click();
            } else {
                var evt = document.createEvent("MouseEvents");
                evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                elm.dispatchEvent(evt);
            }
        }
    };
    this.Toggle = function(e) {
        if (!e) var e = window.event;
        var targ = e.target ? e.target : e.srcElement;

        if (targ._panel && targ._panel.length > 0) {
            var obj_panel = document.getElementById(targ._panel);
            var behavior_id;
            var ex = new Expander();
            ex.objId = targ._panel;
            ex.velocity = targ._veloc;

            if (targ._pre)
                targ._pre();

            if (obj_panel.style.display == 'none') {
                behavior_id = 1;
                obj_panel.style.display = '';

                ex.startValue = 0;
                ex.endValue = targ._height;
            } else {
                behavior_id = 2;
                ex.startValue = 0;
                ex.endValue = 0;
                ex.onComplete = function() { obj_panel.style.display = 'none'; }
            }

            for (var i = 0; i < targ._elements.length; i = i + 3) {
                var elm = document.getElementById(targ._elements[i]);

                if (elm) {
                    switch (elm.nodeName.toLowerCase()) {
                        case "img": elm.src = targ._elements[i + behavior_id]; break;
                        case "a": elm.innerHTML = targ._elements[i + behavior_id]; break;
                        default: elm.innerHTML = targ._elements[i + behavior_id]; break;
                    }
                }
            }

            ex.execute();
        }
    };
    this.PreToggle = function() { };
    this.PostToggle = function() { };
}


//Update view result's
function changeViewStatus() {
  //  document.getElementById('spn_t2').innerHTML = ''
    ShowLightBox('ucEditSmartAgents_cancel_view_LightBox', false);
}
   

function UpdateViewResults(AgentId) {
    _call("UpdateViewResults", { "AgentId": AgentId }, UpdateViewResultsSuccess);
}

function UpdateViewResultsSuccess() {
    HideLightBox("ucEditSmartAgents_cancel_view_LightBox");
    //ShowLightBox("", true);
    window.location.reload(true);
}

function ChangeViewedMessages(AgentId , Link) {
    _call("ChangeViewedMessages", { "AgentId": AgentId }, ChangeViewedMessagesSuccess);
    location.replace(Link);
}

function ChangeViewedMessagesSuccess() {
    
}

function toggleRadioButtons() {
    //div toggle
    var obj_toggle = document.getElementById('ucEditSmartAgents_agentEdit_ShowScanTypes');
    //button toggle
    var obj_btn_toggle = document.getElementById('ucEditSmartAgents_agentEdit_OnceADayCell');
    //cell radio buttons
    var obj_btn_other1 = document.getElementById('ucEditSmartAgents_agentEdit_ThreeTimesCell');
    var obj_btn_other2 = document.getElementById('ucEditSmartAgents_agentEdit_AsEntersCell');
    //email radio buttons
    var obj_btn_other3 = document.getElementById('ucEditSmartAgents_agentEdit_AsEntersEmail')
    var obj_btn_other4 = document.getElementById('ucEditSmartAgents_agentEdit_ThreeTimesEmail');

    if (obj_btn_toggle.checked) {
        obj_toggle.style.display = "block";
    }
    else {
        if (obj_btn_other1.checked) {
            obj_toggle.style.display = "none";
        }
        if (obj_btn_other2.checked) {
            obj_toggle.style.display = "none";
        }
        if (obj_btn_other3.checked) {
            obj_toggle.style.display = "none";
        }
        if (obj_btn_other4.checked) {
            obj_toggle.style.display = "none";
        }
    }
}

function ChangeCategories() {
    this.category = '';
}
ChangeCategories.prototype.ChangeCategory = function(category) {
    this.category = category;

    switch (category) {
        case "v":
            document.getElementById('vihicle').className = "style2 bold";
          
            break;
        case "a":
            document.getElementById('appartment').className = "style2 bold";
            
            break;
        case "s":
            document.getElementById('secondhand').className = "style2 bold";
           
            break;
    }
}
function KeyValuePair()
{
  //'Assigning the Key from the arguments
  this._strKey = (arguments.length == 2) ? arguments[0]: null;
  //'Assigning the Key from the arguments
  this._strValue = (arguments.length == 2) ? arguments[1]: null;
 
  // if parameter is defined, the key is set.
  // if parameter is not defined, the key is retrieved.
  this.Key = function()
  {
    if (arguments.length == 1)
      this._strKey = arguments[0];
    else
      return this._strKey;
  }
  // if parameter is defined, the value is set.
  // if parameter is not defined, the value is retrieved.
  this.Value = function()
  {
    if (arguments.length == 1)
      this._strValue = arguments[0];
    else
      return this._strValue;
  }
  // Params: (KeyValuePair objkvp)
  // Return: boolean
  this.Equals = function(oKV)
  {
    try
    {
      if (oKV.GetType() == this.GetType())
      {
        if (this._strKey == oKV.Key() && this._strValue == oKV.Value())
        {
          return true;
        }
      }
    }
    catch (e)
    {
      throw "(Exception: kvp_e0) Invalid parameter type";
    }
    return false;
  }
  // Return: string
  this.GetType = function()
  {
    return "Library.KeyValuePair";
  }
  // Return: string (delimits the key and value if provided)
  this.ToString = function()
  {
    var strDelimiter = (arguments.length == 1) ? arguments[0]: "";
    return this._strKey + strDelimiter + this._strValue;
  }
}

function SetSelectedAgentItem(agent_id, isFirst) {
    if (agent_id.length == 0) {
        document.getElementById('td_' + agent_id).className = "agent-tab-act";
    }
    else {
        document.getElementById('td_' + agent_id).className = "agent-tab-act";
        if (isFirst == 0) {
            document.getElementById('ucEditSmartAgents_main_tbl').className = "agent-tabs-bg2";
        }
        if (isFirst == 1) {
            document.getElementById('ucEditSmartAgents_main_tbl').className = "agent-tabs-bg1";
        }
    }
}


function Redirect() {
    this._pathRedirection;
}

Redirect.prototype.RedirectFunc = function(str_Path, bl_IsRedirect, bl_IsExecutionTimed, n_ExecutionTime) {
    if (bl_IsRedirect) {
        this._pathRedirection = str_Path;
        if (bl_IsExecutionTimed) {
            setTimeout("window.location = '" + str_Path + "'", 1000 * n_ExecutionTime);
        }
        else {
            window.location = str_Path;
        }
    }
    else {
        window.location.reload(true);
    }
}

/*Validate Amount of Agents*/
function ValidateAmount(category) {
    var amount_agents = document.getElementById('hdnValidateAgents')
    var title_spn = document.getElementById('spn_title_freeze'); 
    var content_spn = document.getElementById('spn');
    var isValid = true;
    var query = amount_agents.value.substring(0);
    var pairs = query.split(";");
    var arr_kvp = [];
    var returnValue = '';
    
    for (var i = 0; i < pairs.length; i++) {
        var position = pairs[i].indexOf(',');
        if (position == -1) continue;
        arr_kvp[pairs[i].substring(0, position)] = pairs[i].substring(position + 1);
    }
    
    for (var i = 0; i < pairs.length; i++) {
        returnValue = arr_kvp[category];        
        break;
    }

    if (returnValue == 5) {
        title_spn.innerHTML = 'יצירת סוכן חכם';
        content_spn.innerHTML = 'אין אפשרות להגדיר יותר מ - 5 סוכנים חכמים <br /> אנא מחק קודם את אחד הסוכנים שכבר הגדרת בעבר ';
        ShowLightBox('ucLoginBarRegistred_smsError_Notes_LightBox', false);
        isValid = false;
    }
    return isValid; 
}

function OnChangePopulation() {
    var Category = document.getElementById('c_ucBoards_create').value;
    
    switch (Category) {
        case "לוח רכב":
            if (ValidateAmount('v')) {
                location.replace('SmartAgents.aspx?qsCateg=vehicles&a=35&t=11');
            }
            break;
        case "לוח נדל\"ן":
            if (ValidateAmount('a')) {
                location.replace('SmartAgents.aspx?qsCateg=appartment&a=35&t=2');
            }
            break;
        case "לוח יד שניה":
            if (ValidateAmount('s')) {
                location.replace('SmartAgents.aspx?qsCateg=secondhand&a=35&t=21');
            }
            break;
    }
}

/*CLEAR ALL VALIDATORS IN EDIT MODEL*/
function clearValidators() {
//    document.getElementById('errorDivSms').style.display = 'none';
//    document.getElementById('showPhoneError').style.display = 'none';
//    document.getElementById('ucEditSmartAgents_agentEdit_CustomValidator2').value = '';
//    if (document.getElementById('ucEditSmartAgents_agentEdit_txtPhone').value.length < 1) {
//        document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms').checked = false;
//    }
}


function set_anchor(anchor) {
    var href_str = document.location.href;
    if (href_str)
        document.location.href = href_str.split('#')[0] + '#' + anchor;
}

function clear_anchor(anchor) {
    var href_str = document.location.href;
    if (href_str)
        document.location.href = href_str.split('#')[0];
}


_clientexec =
{
    ad: undefined,
    param: undefined,
    action: undefined,
    url: undefined,
    commands: {
        listopen: 'document.getElementById(\'list_item_{0}\').onclick();',
        listsave: 'eval(document.getElementById(\'btn_save_ad_row_{0}\').onclick());',
        listdelete: 'eval(document.getElementById(\'btn_delete_ad_row_{0}\').onclick());',
        gallerysave: 'eval(document.getElementById(\'btn_save_ad_gal_{0}\').onclick());',
        gallerydelete: 'eval(document.getElementById(\'btn_delete_ad_gal_{0}\').onclick());',
        innersave: 'eval(document.getElementById(\'btn_save_ad_{0}\').onclick());',
        addcomment: 'document.getElementById(\'txtCommentText_{0}\').value = \'{1}\'.replace(/\\<br\\>/g, \'\\n\'); document.getElementById(\'btn_send_comment_{0}\').onclick()',
        addreply: 'document.getElementById(\'ad_reply_title_{0}\').onclick();',
        toggleadsave: 'document.getElementById(\'list_item_{0}\').onclick();_clientexec.store({ad:\'{0}\',action:\'innersave\'});',
        toggleaddcomment: 'document.getElementById(\'list_item_{0}\').onclick();_clientexec.store({ad:\'{0}\',param:\'{1}\',action:\'addcomment\'});',
        toggleaddreply: 'document.getElementById(\'list_item_{0}\').onclick();_clientexec.store({ad:\'{0}\',action:\'addreply\'});',
        showlightbox: 'setTimeout("ShowLightBox(\'{0}\',false)",1000);',
        replacelightbox: 'setTimeout("HideLightBox(\'{0}\',false); ShowLightBox(\'{1}\',false)",100);',

        test: 'alert(\'{0}\');'
    },
    commandcookie: 'exec_cmd',
    store: function(p) {
        var arr = [];
        var i = 0;
        for (a in p) {
            arr[i++] = a + ":\"" + (a == "param" ? this.parse(p[a], false) : p[a]) + "\"";
        }

        createCookie(this.commandcookie, '{' + arr.join(',') + '}', 1);
    },
    pull: function() {
        var cmd = readCookie(this.commandcookie);
        if (cmd) {
            eraseCookie(this.commandcookie);

            eval('var p =' + cmd);
            if (p.param) {
                p.param = this.parse(p.param, true);
            }

            this.exec(p);
        }
    },
    erase: function() {
        eraseCookie(this.commandcookie);
    },
    hascommand: function() {
        var cmd = readCookie(this.commandcookie);
        if (cmd) {
            return true;
        } else {
            return false;
        }
    },
    exec: function(p) {
        if (p) {
            for (a in p) {
                eval('this.' + a + '=p[a]');
            }
        }

        var cmd = eval('this.commands.' + this.action);
        if (cmd) {
            try {
                eval(String.prototype.format(cmd, this.ad, this.param));
            } catch (ex) { /*alert(ex);*/return false; }
            return true;
        } else {
            return false;
        }
    },
    parse: function(str, unparse) {
        if (!unparse) {
            str = str.replace(/\n/g, "<br>");
            str = escape(str);
        } else {
            str = unescape(str);
        }
        return str;
    }
}

var cl = _clientexec;


function DateValidator(DateNow, NextDate) {
    this.ValidateDates = function() {
        //date to compare with current date
        var day1 = DateNow.substring(0, DateNow.indexOf("/"));
        var month1 = DateNow.substring(DateNow.indexOf("/") + 1, DateNow.lastIndexOf("/"));
        var year1 = DateNow.substring(DateNow.lastIndexOf("/") + 1, DateNow.length);

        //the requested date comparer
        var day2 = NextDate.substring(0, NextDate.indexOf("/"));
        var month2 = NextDate.substring(NextDate.indexOf("/") + 1, NextDate.lastIndexOf("/"));
        var year2 = NextDate.substring(NextDate.lastIndexOf("/") + 1, NextDate.length);
        //the parsed dates
        var currentDate = day1 + "/" + month1 + "/" + year1;
        var freezinDate = day2 + "/" + month2 + "/" + year2;

        var now = new Date(currentDate);
        var nxt = new Date(freezinDate);
        var day = 1000 / 60 / 60 / 24;
        
        var dateDifference = now - nxt;
        dateDifference = Math.ceil((dateDifference / day));


        if (dateDifference >= 0) {
            return false;
        }
        else {
            return true;
        }
    }
}

function IsPhoneValid(cellNumber) {
    _call("IsCellValid",{"CellNumber" : cellNumber}, SuccessValid, cellNumber);
}
//if success
function SuccessValid(context,user_context) {
    document.getElementById('cvalSMS_isvalid').value = context;

    try {
        document.getElementById('ucStep1_ucLightBoxSms_ctl01_hidden1').value = user_context;
    } catch (ex) {
        document.getElementById('ucEditSmartAgents_agentEdit_ucLightBoxSms_ctl01_hidden1').value = user_context;
    }
    
    //alert(context);
    if (context == 0) {
        ShowLightBox('ucStep1_ucLightBoxSms_LightBox');
        ShowLightBox('ucEditSmartAgents_agentEdit_ucLightBoxSms_LightBox');
    } else if (context == 1) {
        try {
            document.getElementById('ucStep1_btnSave').click();
        } catch (ex) {
            document.getElementById('ucEditSmartAgents_agentEdit_btnUpdateAgent').click();
        }
    }
}

function IsPhoneValidEdit(cellNumber) {
    _call("IsCellValid", { "CellNumber": cellNumber }, SuccessValidEdit);
}
//if success
function SuccessValidEdit(contex) {
    
    var chk_sms = document.getElementById('ucEditSmartAgents_agentEdit_IAlowSendSms');
    var chk_ialow = document.getElementById('ucEditSmartAgents_agentEdit_IAlow');
    var phone = document.getElementById('ucEditSmartAgents_agentEdit_txtPhone');
    var prephone = document.getElementById('s_Phone_Obj');
    if (contex == 1) {
        //if phone exists
        if (!chk_ialow.checked) {
            chk_ialow.checked = true;
        }
    }
    else {
        var cellNumber = prephone.value + phone.value;
        chk_ialow.checked = false;
        SendSmsEdit(cellNumber);
    }
}
/*Validate agent create name:*/
//onsuccess validation change name or status
//_validated = true/false
//
function validate_agentName() {
    //alert("validate_agentName");
    var AgentName = document.getElementById('ucStep1_txtAgentName').value;
    
    if (AgentName != 'בחר שם לסוכן') {
        _call("ValidateAgentName", { "Name": AgentName }, OnAgentNameValidationSuccess);
    }
    else {
        _validated = true;
    }
}
/*Validate agent create name:*******************/
//onsuccess validation change name or status
//_validated = true/false
//
function OnAgentNameValidationSuccess(validation) {
    var divValidation = document.getElementById('agent_name');
    var textValue = document.getElementById('ucStep1_txtAgentName');
    
    if (validation == 1) {
        divValidation.style.display = 'block';
        //var f = new setScreenFocus()
        //f.findPositionWithScrollingAndFocus(document.getElementById('div1'));
        divValidation.focus();
        _validated = false;
    }
    else {
        InsertValuesIntoHdn(textValue.value);
        divValidation.style.display = 'none';
        _validated = true;
    }
}

/*Validate agent edit:******************/
//validate if name exists in db ajax call
//
function validate_agentNameEdit() {
    var AgentName = document.getElementById('ucEditSmartAgents_agentEdit_txtAgentName').value;
    //alert("_originalName:" + " " + _originalName);
    //alert("AgentName:" + " " + AgentName);
       
    if (_originalName != AgentName) {
        _call("ValidateAgentName", { "Name": AgentName }, OnAgentNameValidationSuccessEdit);
    }
    else {
        _validated = true;
    }
}
/*Validate agent edit:******************/
//onsuccess validation change name or status
//_validated = true/false
//
function OnAgentNameValidationSuccessEdit(validation) {
    var divValidation = document.getElementById('agent_name');
    var textValue = document.getElementById('ucEditSmartAgents_agentEdit_txtAgentName');

    if (validation == 1) {
        divValidation.style.display = 'block';
        var f = new setScreenFocus()
        f.findPositionWithScrollingAndFocus(document.getElementById('img_upd'));
        _validated = false;
    }
    else {
        divValidation.style.display = 'none';
        _validated = true;
    }
}

//object to set focus on
function setScreenFocus() {
    this.findPositionWithScrollingAndFocus = function(oElement) {
        if (typeof (oElement.offsetParent) != 'undefined') {
            var originalElement = oElement;
            for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
                posX += oElement.offsetLeft;
                posY += oElement.offsetTop;
                if (oElement != originalElement && oElement != document.body && oElement != document.documentElement) {
                    posX -= oElement.scrollLeft;
                    posY -= oElement.scrollTop;
                }
            }
//            if (window.pageYOffset > posY || document.documentElement.scrollTop > posY) {
//                window.scrollTo(posX, posY);
//            }
        }
    }//func
} //object


/*Catch mouse position class:******************/
// Global variables
//
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page
function catchMousePos() {
    this.posX = 0;
    this.posY = 0;
    
    this.init = function() {
        if (document.layers) { // Netscape
            document.captureEvents(Event.MOUSEMOVE);
            document.onmousemove = captureMousePosition;
        } else if (document.all) { // Internet Explorer
            document.onmousemove = captureMousePosition;
        } else if (document.getElementById) { // Netcsape 6
            document.onmousemove = captureMousePosition;
        }

        function captureMousePosition(e) {
            if (document.layers) {
                xMousePos = e.pageX;
                yMousePos = e.pageY;
                xMousePosMax = window.innerWidth + window.pageXOffset;
                yMousePosMax = window.innerHeight + window.pageYOffset;
            } else if (document.all) {
                xMousePos = window.event.x + document.body.scrollLeft;
                yMousePos = window.event.y + document.body.scrollTop;
                xMousePosMax = document.body.clientWidth + document.body.scrollLeft;
                yMousePosMax = document.body.clientHeight + document.body.scrollTop;
            } else if (document.getElementById) {
                xMousePos = e.pageX;
                yMousePos = e.pageY;
                xMousePosMax = window.innerWidth + window.pageXOffset;
                yMousePosMax = window.innerHeight + window.pageYOffset;
            }
        }
    }
}

//******************************************************************************
//Send email suggest to friend 
//
////////////////////////////////////////////////////////////////////////////////
function SuggestToFriend(Reciever, RecieverName, Sender, FreeText, LightBoxId) {
    this._recieverEmail = Reciever;
    this._recieverName = RecieverName;
    this._senderEmail = Sender;
    this._freeText = FreeText;

    this.sendEmail = function() {
        _call("SendAdviseToFriend", { "Reciever": Reciever, "RecieverName": RecieverName, "Sender": Sender, "FreeText": FreeText }, OnEmailSendSuccess);
    }

    function OnEmailSendSuccess() {
        var s = readCookie("LoginCookie");
        
        if (s != null) {
            HideLightBox('ucLoginBarRegistred_suggest_friendLight_LightBox');
        }
        else {
            HideLightBox('ucLoginBar_suggest_friendLight_LightBox');
        }
        
        Show("המלצה לחבר", "תודה שהמלצת על אתר זה וזה", true);
    }
    
    function Show(title, content, IsTime) {
        var content_spn = document.getElementById('spn');
        document.getElementById('spn_title_freeze').innerHTML = title;
        content_spn.innerHTML = content;
        ShowLightBox(LightBoxId, IsTime);
    }
}

//*************************
//get data into the _inputs
//
function get_data(reciever_name_id, reciever_mail_id, sender_name_id, sender_mail_id, main_msg) {
   
    document.getElementById('tblButtons').style.paddingLeft = "5px";
    var _data = _search.split(';');
    var s = readCookie("LoginCookie");
    
    if (s != null) {
        document.getElementById(reciever_name_id).value = '';
        document.getElementById(reciever_mail_id).value = '';
        document.getElementById(main_msg).value = 'כדאי לך לראות את האתר';
    }
    else {
        document.getElementById(reciever_name_id).value = '';
        document.getElementById(reciever_mail_id).value = '';
        document.getElementById(sender_name_id).value = '';
        document.getElementById(sender_mail_id).value = '';
        document.getElementById(main_msg).value = 'כדאי לך לראות את האתר';
    }
    
    if (_data[1] != undefined && _data[0] != undefined) {
        document.getElementById(sender_name_id).value = _data[1];
        document.getElementById(sender_mail_id).value = _data[0];
    }
}
//***************************************************************
//Object printing page
//
//
var mesureScreen = function(url) {
    this._documentHeight = 0;
    this.openWindowWithScroll = function() {
        this._documentHeight = document.body.clientHeight;
        if (this._documentHeight > 507) {
            openWindow(url, "", 757, 585, true);
        }
    }
}
function printAllAds(url) {
    var ms = new mesureScreen(url);
    ms.openWindowWithScroll();
}


function setBackgroundColor(e) {
    if (!e) var e = window.event;

    //alert(e);

}

defaultTextRenderer =
{
    init: function() {
        var _inps = document.getElementsByTagName('input');
        for (var i = 0; i < _inps.length; i++) {
            var _inp = _inps[i];
            if ((_inp.type == 'text' || _inp.type == 'password') && (_inp.attributes["_def"] || _inp.attributes["_err"])) {
                if (_inp.type == 'password') {
                    var def = _inp.attributes["_err"] ? _inp.attributes["_err"].value : _inp.attributes["_def"].value;
                    if (_inp.value.length == 0 || _inp.value == def) {
                        _inp = changeInputType(_inp, 'text', def, false, true);
                       
                    }
                    _inp.setAttribute("_ispass", true);
                }
                this.setevents(_inp, 'focus');
            }
        }
    },
    setevents: function(_inp, _type) {
        if (_inp.addEventListener) {
            _inp.addEventListener('blur', defaultTextRenderer.render, false);
            _inp.addEventListener('focus', defaultTextRenderer.render, false);

        } else {
            _inp.attachEvent('onblur', defaultTextRenderer.render);
            _inp.attachEvent('onfocus', defaultTextRenderer.render);
        }
    },
    render: function(e) {
        if (!e) var e = window.event;

        var targ = e.target ? e.target : e.srcElement;
        var def = targ.attributes["_def"].value;
        if (targ.attributes["_err"]) {
            var err = targ.attributes["_err"].value;
            targ.removeAttribute("_err");
            if (targ.attributes["_errclass"])
                targ.className = targ.className.replace(targ.attributes["_errclass"].value, '');
        }

        switch (e.type) {
            case 'blur':
                if (targ.value.length == 0) {
                    if (targ.attributes["_ispass"]) {
                        targ = changeInputType(targ, 'text', def, false, true);
                        setTimeout("defaultTextRenderer.setevents(document.getElementById('" + targ.id + "'), 'focus')", 200);
                    }
                    targ.value = def;
                }
                break;
            case 'focus':
                if ((def && targ.value == def) || (err && targ.value == err)) {
                    if (targ.attributes["_ispass"]) {
                        targ = changeInputType(targ, 'password', '', false, false);
                        setTimeout("defaultTextRenderer.setevents(document.getElementById('" + targ.id + "'), 'blur')", 200);
                    }
                    targ.value = '';
                }
                break;
        }
    }
}


var toolTip =
{
    id: 'tooltip',
    position: 'bottom left',
    width: 150,

    init: function(initelements) {
        if (!document.getElementById(this.id)) {
            var tt = document.createElement("div");
            tt.id = this.id;
            tt.style.top = tt.style.left = '-100px';
            tt.position = this.position;
            document.body.appendChild(tt);
            tt.style.visibility = 'hidden';
        }
        if (initelements) {
            this.initelements();
        }
    },

    initelements: function(obj) {
        var _elms = obj ? obj : document.body;
        _elms = _elms.getElementsByTagName('*')

        for (var i = 0; i < _elms.length; i++) {
            if (_elms[i].attributes && _elms[i].attributes["_tooltip"]) {
                this.setevents(_elms[i]);
            }
        }
    },

    setevents: function(elm) {

        if (elm.addEventListener) {
            elm.addEventListener('mouseover', toolTip.render, false);
            elm.addEventListener('mousemove', toolTip.render, false);
            elm.addEventListener('mouseout', toolTip.render, false);
        } else {
            elm.attachEvent('onmouseover', toolTip.render);
            elm.attachEvent('onmousemove', toolTip.render);
            elm.attachEvent('onmouseout', toolTip.render);
        }
    },

    render: function(e) {
        if (!e) var e = window.event;

        var targ = e.target ? e.target : e.srcElement;

        var tt = document.getElementById("tooltip");

        switch (e.type) {
            case 'mouseover':
            case 'mousemove':

                var _x = 0;
                var _y = 0;

                while (targ && !targ.attributes["_tooltip"]) {
                    //_x = -10;
                    _y = 15;
                    targ = targ.parentNode;
                }

                if (targ.attributes["title"] && targ.attributes["title"].value != '') {
                    targ.attributes["_tooltip"].value = targ.attributes["title"].value;
                    targ.attributes["title"].value = '';
                }

                if (targ.attributes["_tooltip"].value != '') {
                    tt.innerHTML = targ.attributes["_tooltip"].value;
                    var tmp = targ;


                    if (tt.position.indexOf("top") > -1) {
                        _y -= targ.clientHeight;
                    }
                    if (tt.position.indexOf("bottom") > -1) {
                        _y += targ.clientHeight;
                    }
                    if (tt.position.indexOf("right") > -1) {
                        _x += tt.clientWidth;
                    }
                    if (tt.position.indexOf("left") > -1) {
                        _x -= tt.clientWidth;
                    }

                    if (e.pageX || e.pageY) {
                        _x += e.pageX;
                        _y += e.pageY;
                    }
                    else if (e.clientX || e.clientY) {
                        _x += e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
                        _y += e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
                    }

                    if (_x - tt.clientWidth < 0) 
                        _x += tt.clientWidth;

                    if (_y - tt.clientHeight < 0)
                        _y += tt.clientHeight;


                    tt.style.left = _x + 'px';
                    tt.style.top = _y + 'px';

                    var width = targ.attributes["_width"] && !isNaN(targ.attributes["_width"].value) ? targ.attributes["_width"].value : toolTip.width;

                    if (tt.style.maxWidth != undefined)
                        tt.style.maxWidth = width + 'px';
                    else
                        tt.style.width = tt.clientWidth > width ? width + 'px' : tt.clientWidth + 'px';

                    tt.style.visibility = 'visible';
                }

                e.cancelBubble = true;
                if (e.stopPropagation) e.stopPropagation();

                break;

            case 'mouseout':
                tt.style.visibility = 'hidden';
                tt.innerHTML = '';
                tt.style.top = tt.style.left = '-100px';

                break;
        }
    }
}


window.onload = function() {
    toolTip.init(false);
    defaultTextRenderer.init();
}

function changeInputType(
  oldElm, // a reference to the input element
  iType, // value of the type property: 'text' or 'password'
  iValue, // the default value, set to 'password' in the demo
  blankValue, noFocus) // true if the value should be empty, false otherwise
{
    if (!oldElm || !oldElm.parentNode || (iType.length < 4) ||
    !document.getElementById || !document.createElement) return;
    var isMSIE = /*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
    if (!isMSIE) {
        var newElm = document.createElement('input');
        newElm.type = iType;
    } else {
        var newElm = document.createElement('span');
        newElm.innerHTML = '<input type="' + iType + '" name="' + oldElm.name + '">';
        newElm = newElm.firstChild;
    }
    var props = ['name' , 'id' , 'className' , '_def' , '_err', '_errclass' , '_ispass'];
    for (var i = 0, l = props.length; i < l; i++) {
        if (oldElm[props[i]]) { newElm[props[i]] = oldElm[props[i]]; }
        else if (oldElm.attributes[props[i]]) { newElm.setAttribute(props[i],oldElm.attributes[props[i]].value); }
    }
    // hasFocus is to prevent a loop where onfocus is triggered over and over again
    newElm.hasFocus = false;
    // some browsers need the value set before the element is added to the page
    // while others need it set after
    if (!blankValue) newElm.value = iValue;
    oldElm.parentNode.replaceChild(newElm, oldElm);
    if (!isMSIE && !blankValue) newElm.value = iValue;
    if (!noFocus || typeof (noFocus) == 'undefined') {
        window.tempElm = newElm;
        setTimeout("tempElm.hasFocus=true;tempElm.focus();", 100);
    }
    return newElm;

}



function accordion() 
{
    this.elements = [];
    this.addElements = function() {
        for (var i = 0; i < arguments.length; i++) {
            var elm = arguments[i];
            if(elm && elm.obj1)
                this.elements.push(elm);
        }
    };
    this.init = function() {
        for (var i = 0; i < this.elements.length; i++) {
            if (typeof this.elements[i].obj_toggle != 'object')
                this.elements[i].obj_toggle = document.getElementById(this.elements[i].obj_toggle);

            if (typeof this.elements[i].obj1 != 'object')
                this.elements[i].obj1 = document.getElementById(this.elements[i].obj1);

            if (typeof this.elements[i].obj2 != 'object')
                this.elements[i].obj2 = document.getElementById(this.elements[i].obj2);

            this.setEvent(this.elements[i].obj1);
            this.setEvent(this.elements[i].obj2);

            if (this.elements[i].obj1) {
                this.elements[i].obj1._elements = this.elements;
                this.elements[i].obj1._index = i;
            }
            if (this.elements[i].obj2) {
                this.elements[i].obj2._elements = this.elements;
                this.elements[i].obj2._index = i;
            }
        }
    };
    this.setEvent = function(obj) {
        if (obj) {
            if (obj.addEventListener) {
                obj.addEventListener('click', this.toggle, false);
            } else if (obj.attachEvent) {
                obj.attachEvent('onclick', this.toggle);
            }
        }
    }
    this.toggle = function(e) {
        if (!e) var e = window.event;
        var targ = e.target ? e.target : e.srcElement;

        if (targ && targ._elements) {
            var elms = targ._elements;
            var obj1_txt, obj2_txt, display;

            for (var i = 0; i < elms.length; i++) {
                var elm = elms[i];
                var t_obj = elm.obj_toggle;

                if (t_obj) {
                    obj1_txt = i != targ._index ? elm.obj1_closed : t_obj.style.display == 'none' ? elm.obj1_opened : elm.obj1_closed;
                    obj2_txt = i != targ._index ? elm.obj2_closed : t_obj.style.display == 'none' ? elm.obj2_opened : elm.obj2_closed;

                    display = i != targ._index ? 'none' : t_obj.style.display == 'none' ? '' : 'none';

                    t_obj.style.display = display;

                    if (elm.obj1) {
                        switch (elm.obj1.nodeName.toLowerCase()) {
                            case "img": elm.obj1.src = obj1_txt; break;
                            default: elm.obj1.innerHTML = obj1_txt; break;
                        }
                    }
                    if (elm.obj2) {
                        switch (elm.obj2.nodeName.toLowerCase()) {
                            case "img": elm.obj2.src = obj2_txt; break;
                            default: elm.obj2.innerHTML = obj2_txt; break;
                        }
                    }
                }
            }
        }
    };
    
}

function accordion_element(obj1, obj2, obj1_closed, obj1_opened, obj2_closed, obj2_opened, obj_toggle) {
    this.obj1 = obj1;
    this.obj2 = obj2;
    this.obj1_opened = obj1_opened;
    this.obj2_opened = obj2_opened;
    this.obj1_closed = obj1_closed;
    this.obj2_closed = obj2_closed;
    this.obj_toggle = obj_toggle;
}


function scroller() {
    this.triggers = [];
    this.obj = null;
    this.scrollby = 0;
    this.velocity = 0;
    this.addElements = function() {
        for (var i = 0; i < arguments.length; i++) {
            var elm = arguments[i];
            if (elm && elm.obj)
                this.triggers.push(elm);
        }
    };
    this.init = function() {
            for (var i = 0; i < this.triggers.length; i++) {
                if (typeof this.triggers[i].obj != 'object')
                    this.triggers[i].obj = document.getElementById(this.triggers[i].obj);

                this.triggers[i].obj._element = this.triggers[i];
                this.triggers[i].obj._scroller = this;
                this.setEvent(this.triggers[i].obj);
            }
    };
    this.setEvent = function(obj) {
        if (obj) {
            if (obj.addEventListener) {
                obj.addEventListener('click', this.scroll, false);
            } else if (obj.attachEvent) {
                obj.attachEvent('onclick', this.scroll);
            }
        }    
    };
    this.scroll = function(e) {
        if (!e) var e = window.event;
        var targ = e.target ? e.target : e.srcElement;

        var obj = targ._scroller.obj;
        if (typeof obj != 'object')
            obj = document.getElementById(obj);

        if (obj) {
            var scroll = parseInt(obj.style.left) ? Math.abs(parseInt(obj.style.left)) : 0;

            switch (targ._element.direction) {
                case "<": scroll = (scroll + targ._scroller.scrollby) <= parseInt(obj.style.width) ? scroll + targ._scroller.scrollby : scroll; break;
                case ">": scroll = (scroll - targ._scroller.scrollby) <= 0 ? 0 : (scroll - targ._scroller.scrollby); break;
            }

            obj._scrollto = scroll;
            obj._velocity = targ._scroller.velocity;
            obj._round = 0;

            var o_this = targ._scroller;
            setTimeout(function() { o_this.animate(obj) }, 300);
        }
    };

    this.animate = function(obj) {
        var scroll_from = parseInt(obj.style.left) ? Math.abs(parseInt(obj.style.left)) : 0;
        var scroll_to = obj._scrollto;
        var _d = (scroll_to - scroll_from < 0) ? -1 : 1;
        var _v = obj._velocity = obj._velocity * ++obj._round;

        var left = between(scroll_from + (_v * _d), scroll_from, scroll_to) ? scroll_from + (_v * _d) : scroll_to;
        obj.style.left = (left * -1) + 'px';

        if (left != scroll_to) {
            var o_this = this;
            setTimeout(function() { o_this.animate(obj) }, 50);
        }

    }
}

function scroller_element(obj,direction){
    this.obj = obj;
    this.direction = direction;
}

function preload(link_arr) {
    for (var i = 0; i < link_arr.length; i++) {
        var ifr = document.createElement('iframe');
        ifr.src = link_arr[i];
        ifr.width = 0;
        ifr.height = 0;

        _get('pr').appendChild(ifr);
    }
}

function handle_ad(ad_id, op) {
    var lbid = 'l' + op + 'Ad';

    if (op == 'Bump') {
        ad_bump(ad_id);
    } else {
        _get('hdn_' + lbid).value = ad_id;
        ShowLightBox(lbid + '_LightBox');
    }
}


