// main.js
// general purpose functions

///////////////////////////////////
// jQuery nyroModal plugin settings
///////////////////////////////////
$(function() {
    $.nyroModalSettings({
        debug: false, // Show the debug in the background
        minWidth: 10, // Minimum width
        minHeight: 10, // Minimum height
        ltr: false, // Right to left by default. Put to false for Hebrew or Left to Right language
        galleryLinks: '<a href="#" class="nyroModalPrev">Prev</a><a href="#"  class="nyroModalNext">הבא</a>', // Use .nyroModalPrev and .nyroModalNext to set the navigation link
        css: { // Default CSS option for the nyroModal Div. Some will be overwritten or updated when using IE6
            bg: {
                position: 'absolute',
                overflow: 'hidden',
                top: 0,
                left: 0,
                height: '100%',
                width: '100%',
                zIndex: 100
            },
            wrapper: {
                position: 'absolute',
                top: '50%',
                left: '50%'
            },
            wrapper2: {
            },
            content: {
                overflow: 'auto'
            },
            loading: {
                position: 'absolute',
                top: '50%',
                left: '50%',
                marginTop: '-50px',
                marginLeft: '-50px'
            }
        },
        closeButton: '<a href="#" class="nyroModalClose" id="closeBut" title="סגור">סגור</a>', // Adding automaticly as the first child of #nyroModalWrapper
        contentLoading: '<a href="#" class="nyroModalClose">ביטול</a>', // Loading div content
        contentError: 'התמונה אינה זמינה.<br />אנא נסו מאוחר יותר.<br /><a href="#" class="nyroModalClose">סגור</a>', // Content placed in the loading div in case of error
        endFillContent: function() { // Will be called after filling and wraping the content, before parsing closeSelector and openSelector and showing the content
            if (navigator.appName.indexOf("Microsoft")!=-1) {
                window.location='#';
            }
        }
    });
});

//////////////////////////////*/
// AJAX
///////////////////////////////
function call(func, url, params) {
    http_request = false;
    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }
    if (!http_request) {
        eval(func+"('HTTP_REQUEST_ERROR')");
        //alert('Cannot create XMLHTTP instance');
        return false;
    }
    http_request.onreadystatechange = function() {
        if(http_request.readyState == 4) {
            if (http_request.status == 200) {
                resp = http_request.responseText;
                eval(func+"(resp)");
            } else {
                eval(func+"('ERROR:'+http_request.status)");
            }
        }
    };
    http_request.open('POST', url, true);
    //Send the proper header information along with the request
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http_request.setRequestHeader("Content-length", params.length);
    http_request.setRequestHeader("Connection", "close");
    http_request.send(params);  //fex: "name=john&age=24&height=186"
    return true;
}

///////////////////////////////
function Cur2Sign( currency ) {
///////////////////////////////
// convert currency name to currency sign

    var curSign = "$";
    switch (currency) {
    case "euro":
      curSign = "&euro;";
      break;
    case "yen":
      curSign = "&yen;";
      break;
    case "pound":
      curSign = "&pound;";
      break;
    case "nis":
    case "shekel":
    case "shekels":
    case "NIS":
      curSign = "₪";
      break;
    }
    return curSign;
}

function hfunc(v1,v2,v3,v4) { //temp for show/hide details/prices
    g(v1+'main_'+v4).style.display = v2;
    g(v1+'aura_'+v4).style.display = v2;
    g(v1+'bg_'+v4).style.display = v2;
    g(v1+'con_'+v4).style.display = v2;
    g(v1+'sep_'+v4).style.display = v2;
    g("cat_main_"+app.getCatId(sid)).style.zIndex = v3+"0";
    g("sp"+v4).style.position = "static";
    g("sp"+v4).style.zIndex = v3+"00";
    g("sp"+v4).style.position = "relative";
    if (v1 == "details") {
        g('price_but_'+v4).style.zIndex = 1200
        g('details_but_'+v4).style.zIndex = 1300
    } else {
        g('price_but_'+v4).style.zIndex = 1300
        g('details_but_'+v4).style.zIndex = 1200
    }
    
}

function hideprice(sid) {
    hfunc("price","none","1",sid);
    g('priceleftconnector_'+sid).style.display = "none";
    g('pricerightconnector_'+sid).style.display = "none";
}

function hidedetails(sid) {
    hfunc("details","none","1",sid);
    g('detailsleftconnector_'+sid).style.display = "none";
    g('detailsrightconnector_'+sid).style.display = "none";
}

function showimgpopup(url,title) {
    if (typeof title == "undefined") title="";
    g('popup').style.display = 'block';
    g('popup_content').innerHTML = '<img src="'+url+'" style="cursor:pointer;" onclick="hidepopup()" />';
    g('popup_title').innerHTML = title;
}

function showpopup(content,title) {
    if (typeof title == "undefined") title="";
    g('popup').style.display = 'block';
    g('popup_content').innerHTML = content;
    g('popup_title').innerHTML = title;
}

function hidepopup() {
    g('popup').style.display='none';
}

function showpopup2(content) {
    if (typeof content == "undefined") content='<div style="width:200px;height:30px;text-align:center;">טוען, אנא המתינו...</div>';
    g('popup2').style.display = 'block';
    g('popup2_wait').innerHTML = content;
}

function hidepopup2() {
    if (current<100) {
        wt = setTimeout("hidepopup2()",100);
    } else {
        g("popup2_wait").style.backgroundColor = "#FFF";
        g("popup2_wait").style.border = "2px solid #FFF";
        g('popup2').style.display='none';
    }
}

function emailcheck(str) {
    return (str.indexOf("@")==-1)
        ||(str.indexOf("@")==-1 || str.indexOf("@")==0 || str.indexOf("@")==str.length)
        ||(str.indexOf(".")==-1 || str.indexOf(".")==0 || str.indexOf(".")==str.length)
        ||(str.indexOf("@",(str.indexOf("@")+1))!=-1)
        ||(str.substring(str.indexOf("@")-1,str.indexOf("@"))=="."
           || str.substring(str.indexOf("@")+1,str.indexOf("@")+2)==".")
        ||(str.indexOf(".",(str.indexOf("@")+2))==-1)
        ||(str.indexOf(" ")!=-1)?false:true
}

function popupresponse(text) { //AJAX response text to popup
    tmpVar1 = unescape(text);
    $.nyroModalManual({content: text});    
    //g('sndEmail').innerHTML = text;
    //g('popup_content').innerHTML = text;
}

////////////////////////////////////////
// waiting bar
////////////////////////////////////////
var waitpoints = 1; //number of total collected points (equal to 100%)
var target = 100;
var current = 0;
function setWaitBar(add) {
    if (add!=-1) {
        current = g('wait_status_bar').style.width;
        current = parseInt(current.split('%')[0]);
        target = parseInt(((((current/100)*waitpoints) + add)/waitpoints)*100);
        setWaitBar(-1);
    } else {
        if (current < target) {
            g('wait_status_bar').style.width = current+"%";
            g('wait_status_percent').innerHTML = current+"%";
            current+=4;
            st = setTimeout("setWaitBar(-1)",50);
        } else {
            clearTimeout(st);
            //hidepopup2();
        }
    }
}

//////////////////////////////////////////
// limit input content function
//
// return: limited content
//////////////////////////////////////////
function limit_content(strContent,strLimitTo) {
    for (i=0; i<strContent.length; i++) {
        if (strLimitTo.indexOf(strContent.charAt(i)) == -1) {
            strContent = strContent.replace(strContent.charAt(i),"")
        }
    }
    return strContent
}

function get_canbe(element,PressedKeyCode) {
    //alert(PressedKeyCode)
    if (PressedKeyCode      != 46   // Delete Key
        //&& PressedKeyCode   != 13   // Enter key
        && PressedKeyCode   != 8    // Backspace Key
        && PressedKeyCode   != 9    // Tab Key
        && PressedKeyCode   != 144  // NumPad lock/unlock
        && PressedKeyCode   != 35   // End Key
        && PressedKeyCode   != 36   // Home Key
        && ((PressedKeyCode<37)||(PressedKeyCode>40))   // Navigation Keys
        && ((PressedKeyCode<112)||(PressedKeyCode>123)) // F1 - F12 (Function keys)
        && ((PressedKeyCode<48)||(PressedKeyCode>57))   // Numbers (main)
        && ((PressedKeyCode<96)||(PressedKeyCode>105))  // Numbers (numPad)
    ) return false;
    chk = limit_content(element.value,'0123456789');
    if (element.value!=chk) {
        element.value=chk;
        return false;
    }
    return true;
}
////////////////////////////////////////////

function order_input_empty(id,msg) {
    val = g(id).value;
    if (val == "") {
        $("#order_errors").append("- "+msg+"<br>");
        g(id).style.borderColor = "#F00";
        return true;
    }
    return false;
}

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

function g(id) {
    return document.getElementById(id);
}

function gv(id) {
    return g(id).value;
}

function redirect() {
    showpopup2();
    app.rebuild.all();
    app.OPClick("cancel");    
    hidepopup2();
}

function updateSelect(obj,arr) {
// add one option to select box
//  obj: select box object
//  arr: array of values
//
// return: nothing.
    
    obj.options[obj.options.length] = new Option(arr[0],arr[0])
    for (i=1; i<arr.length; i++)
        if (arr[i]!=arr[i-1])
            obj.options[obj.options.length] = new Option(arr[i],arr[i])
}

function putCategories(arr) {
// adding value in arr (strings) to the category div in the filter (header)
//
// return: nothing.

    $('#categoriesFilter').html("");
    for (i=0; i<arr.length; i++)
        $('#categoriesFilter').append('<div id="cat_'+i+'" onclick="showpopup2(); cat_click(this,true); hidepopup2();" class="notselected-option" style="background-color:transparent;">&nbsp;'+arr[i]+'&nbsp;</div><div style="float:left;">&nbsp;/&nbsp;</div>');
    $('#categoriesFilter').append('<div id="cat_all" onclick="showpopup2(); catall_click(true); hidepopup2();" class="selected-option">&nbsp;הכל&nbsp;</div>');
}

function order_resp(txt) {
    //showpopup("<pre dir=\"ltr\" style=\"font-size:10px\">"+unescape(txt)+"</pre>","Response Succeded!")
}

function setHeight(strSourceId, strTargetId, intDistance) {
/* set element height by other's offset */
    if (typeof intDistance == "undefined") intDistance=0;
    $('#'+strTargetId).css("height",(g(strSourceId).offsetHeight+intDistance)+'px');
}
function setWidth(strSourceId, strTargetId, intDistance) {
/* set element height by other's offset */
    if (typeof intDistance == "undefined") intDistance=0;
    $('#'+strTargetId).css("width",(g(strSourceId).offsetWidth+intDistance)+'px');
}

function repop(type,sid) {
    setHeight(type+"con_"+sid,type+"bg_"+sid)
    setWidth(type+"con_"+sid,type+"bg_"+sid)
    setHeight(type+"con_"+sid,type+"aura_"+sid,10)
    setWidth(type+"con_"+sid,type+"aura_"+sid,20)
    setHeight(type+"con_"+sid,type+"main_"+sid)
    setWidth(type+"con_"+sid,type+"main_"+sid)
}

function calibrating_popup(elementMain,elementButton,elementPopup,intTopRelative,intLeftRelative,intRightRelative) {
// calibrating and positioning the popup relative to the viewed area
//
// conditions:
// 'elementMain' & 'elementPopup' must be inside 'elementButton'
// 'elementPopup' must be inside 'elementMain'
// 'elementMain' must be positioned as fixed and in IE using with position absolute bug
//
// return: side of popup apeared (0-left, 1-right)

    ///// get locations of elements //////
    poph = elementPopup.offsetHeight   //height popup
    popw = elementPopup.offsetWidth    //width popup
    parw=$(window).width()  // viewed area width
    parh=$(window).height() // viewed area height
    xwidth = $(elementButton).width()    //this width
    xheight = $(elementButton).height()  //this height
    xtop = $(elementButton).offset({lite:true,scroll:true}).top - document.body.scrollTop          //this top from window
    xleft = $(elementButton).offset({lite:true,scroll:true}).left - document.body.scrollLeft        //this left from window
    xright = parw - xleft - xwidth    //this right from window
    xbottom = parh - xtop - xheight    //this top from window
    //////////////////////////////////////
    //alert("xtop="+xtop+"\nxleft="+xleft)
    
    if (poph > parh) {
        elementPopup.style.overflow = "auto"
        elementPopup.style.height = parh + 'px'
    }
    
/*
first:
     ------
    |      |XXX
    |      |
     ------

second:
     ------
    |      |
    |      |XXX
     ------
 
third:
        ------
    XXX|      |
       |      |
        ------
 
fourth:
        ------
       |      |
    XXX|      |
        ------
*/
    //if (parseInt(navigator.appVersion)>3) {
        /*if (navigator.appName=="Netscape") {
            if (poph > xbottom+xheight-intTopRelative) {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to fourth")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left",(xleft+xwidth+intRightRelative) +'px')
                    $(elementMain).css("bottom",0 + 'px')
                    side = 1;
                } else {
                    //alert("move to second")
                    $(elementMain).css("right",(xright+xwidth+intLeftRelative) +'px')
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom",0+'px')
                    side = 0;
                }
            } else {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to third")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top",(xtop+intTopRelative) + 'px')
                    $(elementMain).css("left",(xleft+xwidth+intRightRelative) +'px')
                    $(elementMain).css("bottom","auto")
                    side = 1;
                } else {
                    //alert("move to first")
                    $(elementMain).css("right",(xright+xwidth+intLeftRelative) +'px')
                    $(elementMain).css("top",(xtop+intTopRelative) + 'px')
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom","auto")
                    side = 0;
                }
            }
            if ($(elementMain).offset({lite:true,scroll:true,border:true}).top-document.body.scrollTop < 0) $(elementMain).css("top",0+'px')
        } //if (navigator.appName=="Netscape")  */
        
        if (navigator.appName.indexOf("Microsoft")!=-1) { //if the browser is IE
            
            //$(elementPopup).css("position","absolute")
            if (poph > xbottom+xheight-intTopRelative) {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to fourth")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left",(xwidth+intRightRelative-2) +'px')
                    $(elementMain).css("bottom",-2 + 'px')
                    side = 1;
                } else {
                    //alert("move to second")
                    $(elementMain).css("right",(xwidth+intLeftRelative-1) +'px')
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom",-2+'px')
                    side = 0;
                }
            } else {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to third")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top",(intTopRelative-1) + 'px')
                    $(elementMain).css("left",(xwidth+intRightRelative-2) +'px')
                    $(elementMain).css("bottom","auto")
                    side = 1;
                } else {
                    //alert("move to first")
                    $(elementMain).css("right",(xwidth+intLeftRelative-1) +'px')
                    $(elementMain).css("top",(intTopRelative-1) + 'px')
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom","auto")
                    side = 0;
                }
            }
            if ($(elementMain).offset({lite:true,scroll:true,border:true}).top-document.body.scrollTop < 0) $(elementMain).css("top",-xtop+'px')
        } //if (navigator.appName.indexOf("Microsoft")!=-1)
        else //if the browser is not IE
        {
            if (poph > xbottom+xheight-intTopRelative) {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to fourth")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left",(xleft+xwidth+intRightRelative) +'px')
                    $(elementMain).css("bottom",0 + 'px')
                    side = 1;
                } else {
                    //alert("move to second")
                    $(elementMain).css("right",(xright+xwidth+intLeftRelative) +'px')
                    $(elementMain).css("top","auto")
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom",0+'px')
                    side = 0;
                }
            } else {
                if (popw+intLeftRelative > xleft) {
                    //alert("move to third")
                    $(elementMain).css("right","auto")
                    $(elementMain).css("top",(xtop+intTopRelative) + 'px')
                    $(elementMain).css("left",(xleft+xwidth+intRightRelative) +'px')
                    $(elementMain).css("bottom","auto")
                    side = 1;
                } else {
                    //alert("move to first")
                    $(elementMain).css("right",(xright+xwidth+intLeftRelative) +'px')
                    $(elementMain).css("top",(xtop+intTopRelative) + 'px')
                    $(elementMain).css("left","auto")
                    $(elementMain).css("bottom","auto")
                    side = 0;
                }
            }
            if ($(elementMain).offset({lite:true,scroll:true,border:true}).top-document.body.scrollTop < 0) $(elementMain).css("top",0+'px')
        }
    //}
    return side;
}

function urlencode(str) {
str = str.replace(/%/g,'%25').replace(/\+/g,'%2B').replace(/ /g,'+').replace(/!/g,'%21').replace(/"/g,'%22').replace(/\$/g,'%24')
str = str.replace(/'/g,'%27').replace(/\(/g,'%28').replace(/\)/g,'%29').replace(/\*/g,'%2A').replace(/,/g,'%2C').replace(/\//g,'%2F')
str = str.replace(/:/g,'%3A').replace(/</g,'%3C').replace(/=/g,'%3D').replace(/>/g,'%3E').replace(/\?/g,'%3F').replace(/@/g,'%40')
str = str.replace(/\[/g,'%5B').replace(/\\/g,'%5C').replace(/]/g,'%5D').replace(/\^/g,'%5E').replace(/`/g,'%60').replace(/{/g,'%7B')
str = str.replace(/}/g,'%7D').replace(/~/g,'%7E').replace(/#/g,'%23').replace(/&/g,'%26').replace(/;/g,'%3B')
return str
}

function change_spec_bg(e) {
    sid = parseInt($(e).attr("id").split("sp")[1]);
    for (i=0; i<app.viewArr.length; i++)
        if (app.viewArr[i].Id == sid) break;
    var index = i;
    if (app.viewArr[index].bgImg != "images/box-bg0.png") {
        if (app.viewArr[index].bgImg != "images/box-bg1.png") {
            $(e).css("background-image","url(images/box-bg1.png)")
                .attr("alt","לחצו כאן בכדי לצבוע חלונית זו בחזרה לירוק")
                .attr("title","לחצו כאן בכדי לצבוע חלונית זו בחזרה לירוק")
            app.viewArr[index].bgImg = "images/box-bg1.png";
        } else {
            $(e).css("background-image","url(images/box-bg2.png)")
                .attr("alt","לחצו כאן בכדי לצבוע חלונית זו לכחול")
                .attr("title","לחצו כאן בכדי לצבוע חלונית זו לכחול")
            app.viewArr[index].bgImg = "images/box-bg2.png";
        }
    }
}

function subscribe_thanks(text) {
    if (text == "OK") {
        $('#cont_subscribe').html('<div class="text2">תודה שבחרתם להצטרף לרשימת התפוצה שלנו.</div>');
        $('#main_subscribe').css("height","80px");
    } else {
        $('#subscribe_err').html('<div class="text1"><b style="color:red">הבקשה לא נשלחה עקב תקלה. אנא נסו שוב בעוד מספר רגעים.</b></div>');
        $('#main_subscribe').css("height","160px");
    }
}
