var User = {
bSigned: false,
    uid:null,
    name:null,
    username: null,
    email: null,
    pic_square: null
}

var oPosts = {
}

var Custom = {
    FBInit: false,
    FB_ExecuteOnInit: function(oObj) {
        if (!Custom.FBInit)
            setTimeout(function() { Custom.FB_ExecuteOnInit(oObj) }, 100);
        else {
            oObj();
        }
    },
    Facebook_Init: function() {
        window.fbAsyncInit = function() {
            FB.init({ appId: '134434189917761', status: true, cookie: true,
                xfbml: true
            });
            Custom.FBInit = true;
            FB.getLoginStatus(function(response) {
                if (response.session && response.perms) {
                    Custom.Facebook_LoggedIn();
                }
                else Custom.Facebook_LoginMsg.NotLoggedIn();
            });
            (function() {
                var e = document.createElement('script'); e.async = true;
                e.src = document.location.protocol +
          '//connect.facebook.net/he_IL/all.js';
                document.getElementById('fb-root').appendChild(e);
            } ());
        };
        (function() {
            var e = document.createElement('script'); e.async = true;
            e.src = document.location.protocol + '//connect.facebook.net/he_IL/all.js';
            document.getElementById('fb-root').appendChild(e);
        } ());
    },
    Facebook_LoginMsg: {
        LoggedIn: function() {
            $(".loading-connected").css("display", "");
            $(".not-connected").css("display", "");
            $(".connected").css("display", "");

            var cssRuleText = " \
                    div.loading-connected, p.loading-connected, span.loading-connected, a.loading-connected, .loading-connected { \
                        display:none; \
                     } \
                    div.not-connected, p.not-connected, span.not-connected, a.not-connected, .not-connected { \
                        display:none; \
                     } \
                    div.connected { \
                        display:block; \
                     } \
                     a.connected, p.connected, span.connected { \
                        display:inline; \
                     } \
                  ";
            $("<style type='text/css'> " + cssRuleText + " </style>").appendTo("head");
        },
        NotLoggedIn: function() {
            $(".loading-connected").css("display", "");
            $(".connected").css("display", "");
            $(".not-connected").css("display", "");

            var cssRuleText = " \
                    div.loading-connected, a.loading-connected, span.loading-connected, p.loading-connected, .loading-connected { \
                        display:none; \
                     } \
                    div.connected, a.connected, span.connected, p.connected, .connected { \
                        display:none; \
                     } \
                    div.not-connected { \
                        display:block; \
                     } \
                    a.not-connected, p.not-connected, span.not-connected { \
                        display:inline; \
                     } \
                     ";
            $("<style type='text/css'> " + cssRuleText + " </style>").appendTo("head");
        }
    },
    Facebook_LoggedIn: function(oFunc) {
        /* user successfully logged in */
        FB.api(
            {
                method: 'fql.query',
                query: 'select uid, name, username,contact_email,email,pic_square FROM user WHERE uid=' + FB.getSession().uid
            },
            function(response) {
                User.uid = response[0].uid;
                User.name = response[0].name;
                User.username = response[0].username;
                User.email = response[0].email;
                User.pic_square = response[0].pic_square;

                $(".register-user-info-username").text(User.name).css("display", "block");
                $(".register-user-info-uid").val(User.uid);
                $(".register-user-info-email").text(User.email).css("display", "block");
                $(".register-user-info-pic").attr("src", document.location.protocol.replace(/\:/g, "") == "https" ? ("https://graph.facebook.com/" + User.uid + "/picture") : User.pic_square).attr("alt", User.name).css("display", "block");

                User.bSigned = true;
                if (User.bSigned)
                    Custom.Facebook_LoginMsg.LoggedIn();
                else Custom.Facebook_LoginMsg.NotLoggedIn();
                if (oFunc)
                    oFunc(User.bSigned);
            }
        );
    },
    Facebook_Login: function() {
        FB.login(function(response) {
            if (response.session && response.perms)
                Custom.Facebook_LoggedIn(function() { });
        },
            { perms: 'read_stream,publish_stream,offline_access,email' }
        );
    },
    Facebook_Logout: function() {
        FB.logout(function(response) {
            Custom.Facebook_LoginMsg.NotLoggedIn();
        });
    },
    FacebookForum: {
        bInAction: false,
        oSendingObj: null,
        ErrorTimeout: 0,
        SendInterval: 0,
        Delete: function(oObj) {
            if (confirm("האם אתה בטוח שברצונך למחוק?")) {
                var oItem = $(oObj).parents('.forum-feed-item:first');
                var sId = $(oItem).attr("id").replace("p-", "") * 1;
                $.ajax({
                    type: "POST",
                    cache: false,
                    url: "/he/getStream.aspx?sFunc=Delete&obj=Facebook&id=" + sId,
                    dataType: "text",
                    success: function(sJSON) {
                        $(oItem).remove();
                    }
                });
            }
        },
        Post: function(oObj) {

            if (!Custom.FacebookForum.bInAction) {
                Custom.FacebookForum.bInAction = true;
                Custom.FacebookForum.oSendingObj = oObj;
                if (oObj == null) {
                    var oPost = { to: $("#feed-container"), ifbid: User.uid, sName: User.name, sText: $("textarea[name='sText']").val(), sMedia: $("input[name='sMedia']").val(), dCreated: new Date() };
                    $("#small-loader").css("display", "inline");
                    $(".forum-post-button").css("opacity", "0.5");
                }
                else {
                    var oPost = { to: $(oObj), ifbid: User.uid, sName: User.name, sText: $("textarea[name='sText-replay']").val(), sMedia: $("input[name='sMedia-replay']").val(), dCreated: new Date() };
                    /*$("#small-loader").css("display", "inline");*/
                    $(".forum-postreplay-button").css("opacity", "0.5");
                }

                var fDo = function() {

                    if (oObj == null) {
                        var sValue = $('#post-input').val();
                        var sDefaultVal = $('#post-input').attr('data-default');
                        if ((sValue == '' || sValue == sDefaultVal))
                            oPost.sText = '';
                    }

                    var sParams = "ifbid=" + oPost.ifbid + "&sName=" + encodeURIComponent(oPost.sName) + "&sText=" + encodeURIComponent(oPost.sText) + "&sMedia=" + encodeURI(oPost.sMedia);
                    if (oObj != null) {
                        sParams += ("&pid=" + parseInt((oObj).parents(".forum-feed-item:last").get(0).id.substring(2)));
                    }

                    var params = {};
                    params['message'] = oPost.sText;
                    params['name'] = "מתוך פורום ירין שחף";
                    params['description'] = '';
                    params['link'] = 'http://www.yarin-shahaf.co.il/פורום';
                    params['picture'] = 'http://www.yarin-shahaf.co.il' + oPost.sMedia;
                    params['caption'] = '';
                    FB.api('/me/feed', 'post', params, function(response) {
                        if (!response || response.error) {
                            alert('תקלה בשליחה לפייסבוק');
                        }
                    });
                    if (oObj != null) {
                        var iId = $(oObj).parents(".forum-feed-item:first").children(".picture-container").children("img").attr("src").split('/')[3] * 1;
                        if (User.uid != iId) {
                            FB.api('/' + iId + '/feed', 'post', params, function(response) {
                                if (!response || response.error) {
                                    alert('תקלה בשליחה לפייסבוק');
                                }
                            });
                        }

                    }

                    $.ajax({
                        type: "POST",
                        cache: false,
                        url: "/he/getStream.aspx?sFunc=Post&obj=Facebook",
                        dataType: "text",
                        data: sParams,
                        success: function(sJSON) {
                            $("#small-loader").css("display", "none");

                            if (oObj == null) {
                                $('#video-selection').css('display', 'none');
                                $('#photo-selection').css('display', 'none');
                                $('#post-input').css('height', '67px');
                                $('#post-input').attr('data-default', '');

                                Custom.FacebookForum.Focus($('#post-input'));
                                Custom.FacebookForum.Blur($('#post-input'));
                            }
                            if (oObj == null)
                                $(".forum-post-button").css("opacity", "1");
                            else
                                $(".forum-postreplay-button").css("opacity", "1");

                            eval('var oPosts = ' + sJSON);
                            oPost = oPosts.pop();
                            if (oObj == null)
                                oPost.to = $("#feed-container");
                            else
                                oPost.to = $(oObj).parents(".forum-feed-item:first");

                            Custom.FacebookForum.AddItem(oPost, oPost.pid != 0);
                            if (oObj == null) {
                                $("textarea[name='sText']").val('');
                                $("#sMedia").val('');
                                $("#photo-link-input").val('');
                                $("#video-link-input").val('');
                                Custom.FacebookForum.Blur($("textarea[name='sText']"));
                            }
                            else
                                $(oObj).remove();
                            Custom.FacebookForum.bInAction = false;
                            clearTimeout(Custom.FacebookForum.ErrorTimeout);
                        }
                    });
                    /*Custom.FacebookForum.ErrorTimeout = setTimeout(function() {
                    if (Custom.FacebookForum.bInAction)
                    Custom.FacebookForum.PostError('שגיאה כללית, אנא נסה שנית מאוחר יותר');
                    }, 10000);*/
                };

                if ($("#photo-link-input").val() != '') {
                    Custom.FacebookForum.Photo.Post();
                    Custom.FacebookForum.SendInterval = setInterval(function() {
                        if ($("#sMedia").val() != '') {
                            oPost.sMedia = $("#sMedia").val();
                            clearInterval(Custom.FacebookForum.SendInterval);
                            fDo();
                        }
                    }, 300);
                }
                else if ($('#video-link-input').val() != '') {
                    $("#sMedia").val($('#video-link-input').val());
                    oPost.sMedia = $("#sMedia").val();
                    fDo();
                }
                else fDo();
            }
        },
        PostError: function(sMsg) {
            Custom.FacebookForum.bInAction = false;
            $("#small-loader").css("display", "none");
            if (Custom.FacebookForum.oSendingObj == null)
                $(".forum-post-button").css("opacity", "1");
            else
                $(".forum-postreplay-button").css("opacity", "1");
            Custom.FacebookForum.oSendingObj = null;
            alert(sMsg);
        },
        RenderReplay: function(oObj) {
            $("#feed-container").find(".forum-feed-replay").remove();
            Custom.FacebookForum.AddReplay($(oObj).parents(".forum-feed-item:first"));
        },
        AddReplay: function(oObj) {
            if ($(oObj).find(".forum-feed-replay").length == 0)
                $(oObj).append('<div class="forum-feed-item forum-feed-replay"><span class="picture-container"><img src="' + document.location.protocol + '//graph.facebook.com/' + User.uid + '/picture" alt="" /></span><div class="text-container"><textarea name="sText-replay" style="height:47px;width:283px;float:right"></textarea><input type="hidden" name="sMedia-replay" value="" /><span style="padding-right:6px;float:right;padding-top:2px"><img src="/images/default/replay.jpg" alt="הגב" class="forum-postreplay-button" onclick="Custom.FacebookForum.Post($(this).parents(\'.forum-feed-replay:first\'));" /></span></div></div>');
        },
        Render: function(oObj) {
            $("#fb-moreposts").remove();
            $(oObj).attr("data-offset", ($(oObj).attr("data-offset") || 0) * 1 + 20);
            var iOffset = (($(oObj).attr("data-offset") || 0) * 1 - 20);
            $.ajax({
                type: "POST",
                cache: false,
                url: "/he/getStream.aspx",
                data: "obj=Facebook&sFunc=GetPosts&iOffset=" + iOffset,
                dataType: "text",
                success: function(sJSON) {
                    eval('var oPosts = ' + sJSON);
                    $(oPosts).each(function() {
                        if (this.pid == 0)
                            this.to = $(oObj);
                        else this.to = $("#p-" + this.pid);
                        Custom.FacebookForum.AddItem(this, true);
                    });
                    if (oPosts.length == 20) {
                        $(oObj).append('<div id="fb-moreposts" class="fb-container" style="float:right;width:100%;color:#3B5998;text-align:center;cursor:pointer" onclick="Custom.FacebookForum.Render($(\'#feed-container\'))"><span class="fb-title">פרסומים נוספים</span><img src="/images/default/fb-forum-arrow-down.jpg" alt="" style="float: right;padding-top:10px;padding-right:4px" /></div>');
                    }
                }
            });
        },
        PlayMovie: function(oItem, sId) {
            var sHeight = $(oItem).children(".preview").height() * 2.3;
            var sWidth = $(oItem).children(".preview").width() * 2.3;
            var sObj = '<object style="height: ' + sHeight + 'px; width: ' + sWidth + 'px"><param name="movie" value="http://www.youtube.com/v/' + sId + '"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed src="http://www.youtube.com/v/' + sId + '" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' + sWidth + '" height="' + sHeight + '"></object>';
            $(oItem).html(sObj);
        },
        AddItem: function(oPost, bLast) {
        var sDelete = "";
        if (top != self) {
            try {
                if (top.location.href)
                    sDelete = '<img src="/images/default/forum-btn-delete.png" class="delete-icon" onclick="Custom.FacebookForum.Delete(this)" />';
            } catch (e) {
            }
        }        
            var sMediaTag = "";
            if (oPost.sMedia != "") {
                if (oPost.sMedia.toLowerCase().indexOf('youtube') > -1) {
                    //Movie
                    var sId = oPost.sMedia.slice(oPost.sMedia.lastIndexOf('=') + 1, oPost.sMedia.length);

                    sMediaTag = '<span onclick="Custom.FacebookForum.PlayMovie(this,\'' + sId + '\')" style="cursor:pointer"><img class="preview" src="http://i2.ytimg.com/vi/' + sId + '/default.jpg" alt="" /><img src="/images/default/video-play-icon.png" style="position:absolute;left:50px;top:30px;" alt=""/></span>';
                }
                else sMediaTag = '<img class="preview" src="' + oPost.sMedia + '" alt="" />';
            }
            var sPost = '<div id="p-' + oPost.id + '" class="forum-feed-item"><span class="picture-container"><img src="' + document.location.protocol + '//graph.facebook.com/' + oPost.ifbid + '/picture" alt="" /></span><div class="text-container"><span class="forum-post-name">' + oPost.sName + '&nbsp;' + sDelete + '</span><div class="forum-post-text">' + oPost.sText + '<div style="float:right;padding-left:6px;position:relative">' + sMediaTag + '</div></div><div class="forum-post-actions" style="clear:both"><span onclick="Custom.FacebookForum.RenderReplay(this)" class="forum-post-replay connected">הגב</span><span class="connected"> · </span><span class="forum-post-date">' + oPost.dCreated + '</span></div></div></div>';
            if (bLast) {
                $(oPost.to).append(sPost);
            }
            else
                $(oPost.to).prepend(sPost);
        },
        Focus: function(oMe) {
            if ($(oMe).val() == $(oMe).attr("data-default"))
                $(oMe).val('');
            $(oMe).css('color', 'black');
        },
        Blur: function(oMe) {
            if ($(oMe).val() == '') {
                $(oMe).val($(oMe).attr("data-default"));
                $(oMe).css('color', '#777777');
            }
        },
        PostPhoto: function() {
            $('#video-selection').css('display', 'none');
            $('#post-input').css('height', '20px');
            $('#photo-selection').css('display', 'block');
            Custom.FacebookForum.Focus($('#post-input'));
            $('#post-input').attr('data-default', 'כתוב משהו על תמונה..');
            Custom.FacebookForum.Blur($('#post-input'));
        },
        PostVideo: function() {
            $('#photo-selection').css('display', 'none');
            $('#post-input').css('height', '20px');
            $('#photo-link-input').val('');
            $('#video-selection').css('display', 'block');
            Custom.FacebookForum.Focus($('#post-input'));
            $('#post-input').attr('data-default', 'כתוב משהו על וידאו..');
            Custom.FacebookForum.Blur($('#post-input'));
        },
        Photo: {
            Post: function() {
                var sValue = $('#photo-link-input').val();
                var sDefaultVal = $('#post-input').attr('data-default');
                if (sValue == '' || sValue == sDefaultVal) {
                    alert('הקישור אינו מתאים');
                    return false;
                }
                $('#form-photo').submit();
            },
            Cancel: function() {
                $('#photo-link-input').val($('#sMedia').val());
            }
        }
    },
    Submit_ContactForm: function() {

        var aErrors = [];
        var sFirstname = $("#frmContactFirstname").val();
        var sLastname = $("#frmContactLastname").val();
        var sPhone = $("#frmContactPhone").val();
        var sEmail = $("#frmContactEmail").val();

        /* if (sFirstname.replace(/\s/gi, "") == "")
        aErrors.push("שם פרטי");
        if (sLastname.replace(/\s/gi, "") == "")
        aErrors.push("שם משפחה");*/
        if (sPhone.replace(/\s/gi, "") == "")
            aErrors.push("טלפון");
        /*if (sEmail.replace(/\s/gi, "") == "")
        aErrors.push("אימייל");*/

        if (aErrors.length) {
            //alert("ישנם שדות שלא מילאת:\n\n" + aErrors.join("\n"));
            alert("חובה למלא טלפון");
            return false;
        }

        var sParams = $("#frmContact").serialize();

        var oQs = new QueryString();

        if (typeof (SESSION_keyword) == "undefined")
            SESSION_keyword = "";

        if (typeof (SESSION_campaign) == "undefined")
            SESSION_campaign = "";

        var minisiteReferer = SESSION_keyword;
        var sCampaign = SESSION_campaign;
        sParams += "&minisiteReferer=" + escape(minisiteReferer) + "&campain=" + escape(sCampaign);

        $.ajax({
            type: "POST",
            cache: false,
            url: "/he/getXML.aspx?sFunc=GetContactForm&obj=Admin_ContactList",
            dataType: "xml",
            data: sParams,
            success: function(xml) {
                $("#frmContactContent").css("display", "none");
                $("#frmContactSuccess").css("display", "block");
                $("#framethankyou").get(0).src = "/thankyou.html";
                $("#frmContact").get(0).reset();

                setTimeout(function() {
                    $("#frmContactSuccess").css("display", "none");
                    $("#frmContactContent").css("display", "block");
                }, 3000);

            }
        });
        return true;
    },

    TurnClickable: function(sObj, sChild) {
        $(sObj).bind({
            mouseenter: function() {
                $(this).find(sChild).toggleClass('hover');

            },
            mouseleave: function() {
                $(this).find(sChild).toggleClass('hover');
            },
            click: function() {
                document.location = $(this).find(sChild).find("a:first").attr("href");
            }
        }).css("cursor", "pointer");

    },

    CurrentPageMenuItem: null,
    InitMenu: function() {

        var oMenuItems = $("#lstTopMenu").children();
        oMenuItems.find(".empty").remove();
        if (!oMenuItems.filter(".selected").length) {
            /*
            var aRes = /\/(\d+)\//gi.test(location.href);
            if (aRes)
            {
            var iRes = RegExp.$1*1;
            */

            var aLoc = decodeURIComponent(location.href).split("/");
            var sUrlOuter = "";
            if (aLoc.length == 7) {
                var sUrl = aLoc[0] + "//" + aLoc[2] + "/" + aLoc[3] + "/" + aLoc[4] + "/" + aLoc[5] + "/";
                sUrlOuter = aLoc[0] + "//" + aLoc[2] + "/" + aLoc[3] + "/";
                $("#lstTopMenu").find("A[href='" + sUrl + "']").css("color", "#ff668f");
            } else if (aLoc.length == 6) {
                var sUrl = aLoc[0] + "//" + aLoc[2] + "/" + aLoc[3] + "/" + aLoc[4] + "/";
                sUrlOuter = aLoc[0] + "//" + aLoc[2] + "/" + aLoc[3] + "/";
                $("#lstTopMenu").find("A[href='" + sUrl + "']").css("color", "#ff668f");
            } else if (aLoc.length == 5) {
                sUrlOuter = aLoc[0] + "//" + aLoc[2] + "/" + aLoc[3] + "/";
            } else if (aLoc.length == 4) {
                sUrlOuter = "/";
            }

            sUrlOuter = sUrlOuter.replace(location.host, "").replace(/http\:\/\//gi, "");
            if (sUrlOuter != "") {
                $("#lstTopMenu").find("A[href='" + sUrlOuter + "']").parents("LI:first").addClass("selected");
            }
        }

        var oItem = $("#lstTopMenu");
        var oListItems = oItem.children();
        oItem.children("li:last").children("span").addClass("last");
        oListItems.each(function(idx) {
            this.style.zIndex = (oListItems.length + 5 - (idx + 1).toString());
        });

        Custom.CurrentPageMenuItem = oItem.children(".selected");
        var oSelectedItem = Custom.CurrentPageMenuItem.get(0);

        oItem = $("#lstTopMenu");
        Custom.CurrentPageMenuItem.each(function() {

            $(this).children("DIV.submenu").find("A").each(function() {

                //$(this).addClass("selected");
                //$(this).find("A").each(function() {



                if (aLoc.join("/") == this.href) {

                    $(this).css("color", "#ff668f");
                }
                //});

            });

            var iWidth = (getLeft(oSelectedItem) - getLeft(oSelectedItem.parentNode) + getLeft(oItem.get(0).parentNode) - getLeft(oItem.get(0).parentNode.parentNode) + oSelectedItem.offsetWidth);
            if ($(oSelectedItem).parents(":.Marker:first").length)
                iWidth += ($(oSelectedItem).parents(":.Marker:first").position().left - $($(oSelectedItem).parents(":.Marker:first").get(0).parentNode.parentNode).position().left);

            $("#breadcrumbs").html("<div style=\"position:relative;width:" + iWidth + "px\">" + $(this).children("DIV.submenu").html() + "</div>").find(".Marker").css("width", iWidth + "px");
        });

    },

    IntervalShowCurrentPageMenuItem: null,
    OutMenu: function() {

        try { clearInterval(Custom.IntervalShowCurrentPageMenuItem) }
        catch (e) { }

        Custom.IntervalShowCurrentPageMenuItem = setInterval(function() {

            try { clearInterval(Custom.IntervalShowCurrentPageMenuItem) }
            catch (e) { }

            $("#lstTopMenu").children().removeClass("selected");
            Custom.CurrentPageMenuItem.each(function() {
                $(this).addClass("selected");
                var oSelectedItem = this;
                oItem = $("#lstTopMenu");

                var iWidth = (getLeft(oSelectedItem) - getLeft(oSelectedItem.parentNode) + getLeft(oItem.get(0).parentNode) - getLeft(oItem.get(0).parentNode.parentNode) + oSelectedItem.offsetWidth);
                if ($(oSelectedItem).parents(":.Marker:first").length)
                    iWidth += ($(oSelectedItem).parents(":.Marker:first").position().left - $($(oSelectedItem).parents(":.Marker:first").get(0).parentNode.parentNode).position().left);

                $("#breadcrumbs").html("<div style=\"width:" + iWidth + "px\">" + $(this).children("DIV.submenu").html() + "</div>");
            });

        }, 200);
    },

    HoverMenu: function(ev) {

        try { clearInterval(Custom.IntervalShowCurrentPageMenuItem) }
        catch (e) { }

        var oEl = window.addEventListener ? ev.target : ev.srcElement;

        if (oEl.tagName != "UL") {
            oEl = $(oEl).parents("LI:first");
        } else {
            oEl = $(oEl);
        }

        $("#lstTopMenu").children().removeClass("selected");
        oEl.addClass("selected");

        var oSelectedItem = oEl.get(0);

        if (typeof (oSelectedItem) == "undefined")
            return;

        oItem = $("#lstTopMenu");

        var iWidth = (getLeft(oSelectedItem) - getLeft(oSelectedItem.parentNode) + getLeft(oItem.get(0).parentNode) - getLeft(oItem.get(0).parentNode.parentNode) + oSelectedItem.offsetWidth);
        if ($(oSelectedItem).parents(":.Marker:first").length)
            iWidth += ($(oSelectedItem).parents(":.Marker:first").position().left - $($(oSelectedItem).parents(":.Marker:first").get(0).parentNode.parentNode).position().left);

        $("#breadcrumbs").html("<div style=\"position:relative;width:" + iWidth + "px\">" + oEl.children("DIV.submenu").html() + "</div>");

    },

    HoverBreadCrumbs: function() {
        try { clearInterval(Custom.IntervalShowCurrentPageMenuItem) }
        catch (e) { }
    },

    OutBreadCrumbs: function() {
        Custom.OutMenu();
    },

    InitBreadCrumbs: function() {
        $(".lstBreadCrumbs").each(function() {
            $(this).children(":last").addClass("last");
        });
    },

    LstClips_Page: 1,
    LstClips_ItemPerPage: 2,
    LstClips_PageCount: 0,
    LstClips_SwitchWidth: 481,
    LstClips_InAction: false,

    InitLstClip: function() {

        Custom.LstClips_PageCount = Math.ceil($("#lstClips").children("span").length / Custom.LstClips_ItemPerPage);

        var oSpans = $("#lstClips").children("SPAN");
        var aSpans = [];
        oSpans.each(function() {
            aSpans.push(this);
        });

        aSpans.reverse();
        for (var i = 0; i < aSpans.length; i++)
            document.getElementById("lstClips").appendChild(aSpans[i]);

        Custom.ShowLstClipsPage(1);
    },

    bFirstShowLstClipsPage: true,

    ShowLstClipsPage: function(iPage) {

        if (Custom.bFirstShowLstClipsPage) {
            Custom.bFirstShowLstClipsPage = false;
            var aElements = [];
            $("#lstClips").children().each(function() {
                aElements.push(this);
            });
            for (var i = aElements.length - 1; i >= 0; i--)
                $("#lstClips").get(0).appendChild(aElements[i]);
        }

        Custom.LstClips_Page = iPage || Custom.LstClips_Page;
        Custom.LstClips_PageCount = Math.ceil($("#lstClips").children().length / Custom.LstClips_ItemPerPage);

        if (Custom.LstClips_Page == 1) {
            $("#lstClipsNext").removeClass("arrow-right-hover");
        } else {
            $("#lstClipsNext").addClass("arrow-right-hover");
        }

        if (Custom.LstClips_Page == Custom.LstClips_PageCount) {
            $("#lstClipsPrev").removeClass("arrow-left-hover");
        } else {
            $("#lstClipsPrev").addClass("arrow-left-hover");
        }

        Custom.LstClips_InAction = true;

        $("#lstClips").animate({
            marginLeft: ((((Custom.LstClips_Page - 1) * Custom.LstClips_SwitchWidth)) * -1) + "px"
        }, 600, function() {
            Custom.LstClips_InAction = false;
        });

    },

    LstClips_Prev: function() {

        if (Custom.LstClips_InAction)
            return;

        if (Custom.LstClips_Page > 1) {
            Custom.LstClips_Page--;
            Custom.ShowLstClipsPage();
        }
    },

    LstClips_Next: function() {

        if (Custom.LstClips_InAction)
            return;

        if (Custom.LstClips_Page < Custom.LstClips_PageCount) {
            Custom.LstClips_Page++;
            Custom.ShowLstClipsPage();
        }
    },

    GalleryThumbnailsPage: 1,
    GalleryThumbnailsPageCount: null,
    GalleryThumbnailsPerPage: 5,

    GalleryInAction: false,
    GalleryThumbnailsNextPage: function() {

        if (Custom.GalleryInAction)
            return;

        if (Custom.GalleryThumbnailsPage < Custom.GalleryThumbnailsPageCount) {
            Custom.GalleryThumbnailsPage++;

        }
        else {
            return;
        }
        Custom.InitGalleryThumbnails();
    },
    GalleryThumbnailsPrevPage: function() {

        if (Custom.GalleryInAction)
            return;

        if (Custom.GalleryThumbnailsPage == 1)
            return;
        else
            Custom.GalleryThumbnailsPage--;
        Custom.InitGalleryThumbnails();
    },

    bFirstInitGalleryThumbnails: true,
    InitGalleryThumbnails: function() {

        Custom.GalleryThumbnailsPageCount = Math.ceil($("#galsc").children().length / Custom.GalleryThumbnailsPerPage);

        if (Custom.bFirstInitGalleryThumbnails) {
            Custom.bFirstInitGalleryThumbnails = false;

            var sPage = document.location.href.split('/')[6];
            if (sPage.indexOf("#") > -1) {
                sPage = sPage.substring(0, sPage.indexOf("#"));
            }
            var iGalleryOrder = $("#galsc").find("a[href='"+decodeURIComponent(sPage)+"']").parent().prevAll().length || 1;
            Custom.GalleryThumbnailsPage = Math.max(1, Math.ceil(iGalleryOrder / Custom.GalleryThumbnailsPerPage));

            $("#galsc").css("marginLeft", (((((Custom.GalleryThumbnailsPage - 1) * 505)) * -1)) + "px");

        }

        if (Custom.GalleryThumbnailsPage == 1) {
            $("#galnext").get(0).src = "/images/default/bg-arrow-nav2-right-disabled.gif";
        } else {
            $("#galnext").get(0).src = "/images/default/bg-arrow-nav2-right.gif";
        }

        if (Custom.GalleryThumbnailsPage == Custom.GalleryThumbnailsPageCount) {
            $("#galprev").get(0).src = "/images/default/bg-arrow-nav2-left-disabled.gif";
        } else {
            $("#galprev").get(0).src = "/images/default/bg-arrow-nav2-left.gif";
        }

        Custom.GalleryInAction = true;

        $('#galsc').animate({
            marginLeft: (((((Custom.GalleryThumbnailsPage - 1) * 505)) * -1)) + "px"
        }, 600, function() {
            Custom.GalleryInAction = false;
        });

        $("#lstGalleryThumbnails").find("a").each(function(index) {

            $(this).bind("click", function() {
                var sHref = this.href;
                if (sHref.lastIndexOf("#") > -1) {
                    sHref = sHref.substring(0, sHref.lastIndexOf("#"));
                }
                location.href = sHref + "#" + document.documentElement.scrollTop;
                return false;
            });
        });
    },

    HP: {
        InitLstArticles: function() {
            $("#lstArticles").children(":odd").addClass("last").parent().find("P").each(function() {
                this.innerHTML = Cut(this.innerHTML, 60);
            }); ;
        },

        InitLstMagazineItems: function() {
            $("#lstMagazineItems").children(":odd").addClass("last").parent().css("paddingBottom", "5px").find("P").each(function() {
                this.innerHTML = Cut(this.innerHTML, 60);
            });
        },

        InitLstCustomerService: function() {
            $("#lstCustomerService").children(":odd").addClass("last");
        },
        InitLstDownloadContent: function() {
            $("#lstDownloadContent").children(":odd").addClass("last");
        },
        InitTblLastCourses: function() {
            $("#tblLastCourse").find("TR:even").addClass("bg2");
        },

        InitCalendarEvents: function() {

        },

        OpenHelperLesson: function(oEvent, props) {

            var oSourceEl = window.addEventListener ? oEvent.target : oEvent.srcElement;

            var oEl = window.addEventListener ? oEvent.target : oEvent.srcElement;
            if ($(oEl).hasClass("framework"))
                return;

            oEl = $(oEl).hasClass("col") ? oEl : $(oEl).parents(".col:first").get(0);
            var iDay = $(oEl).find(".time").html();

            if (isNaN(iDay) || iDay == null)
                return;

            var oCalendar = Custom.HP.CalendarsGlobal[props.id];
            if (props.showphone) {
                $("#lessonsdate").val(iDay + "." + oCalendar.Month + "." + oCalendar.Year);
            }

            var oEventDay = null;

            $.each(oCalendar.Events, function(idx) {
                if (parseInt(this.Day) + 1 == parseInt(iDay))
                    oEventDay = this;
            });

            var s = "<h4>אין ארועים ליום זה</h4>";
            if (oEventDay) {
                s = "";
                if ($(oSourceEl).hasClass("enabled")) {
                    var sTime = oSourceEl.innerHTML.indexOf(":") > -1 ? oSourceEl.innerHTML.substring(0, oSourceEl.innerHTML.indexOf(":") + 3) : "";
                    $("#lessonstime").val(sTime);
                    var sTrainerName = "";


                    var a = "One,Two,Three".split(",");
                    $.each(a, function(i) {
                        if (oEventDay["Text" + a[i]] != "" || oEventDay["TrainerName" + a[i]] != "") {

                            if (sTime == oEventDay["Text" + a[i]]) {
                                /*
                                s += "<div " + (oEventDay["bDisableHour" + a[i]] == "true" ? " class='disabled'" : " class='enabled'") + "><strong>שעה:</strong> " + oEventDay["Text" + a[i]];
                                if (oEventDay["TrainerName" + a[i]] != "")
                                s += ", <strong>שם המדריך:</strong> " + oEventDay["TrainerName" + a[i]];
                                s += "</div>";
                                */
                                sTrainerName = oEventDay["TrainerName" + a[i]];
                            }
                        }
                    });

                    if (props.id == "CalendarId1") {

                        s += "בכדי לתאם יום צילום לתאריך " + iDay + "/" + oCalendar.Month + "/" + oCalendar.Year + (sTime != "" ? " בשעה " + sTime : "") + "<br/><strong>אנא התקשרי לסטודיו בטלפון 03-5230480<br/>בימים א-ה 10:30-18:00<br/>ביום ו 09:30-12:30</strong><br/><br/>";
                    } else if (props.id == "CalendarId2") {
                        s += "יצירת קשר לתיאום שיעור חיזוק ביום " + iDay + "/" + oCalendar.Month + "/" + oCalendar.Year + (sTime != "" ? " בשעה " + sTime : "") + " עם " + sTrainerName + "<br/><strong>אנא מלאי מס טלפון נייד ואנו נשוב אלייך בהקדם האפשרי</strong><br/><br/>";
                    }

                }
            }

            if (s != "") {
                $("#" + props.id).find(".helper_lesson").find(".info").html(s);
                $("#" + props.id).find(".helper_lesson").css("display", "block");
            }

        },

        RegisterHizuk: function() {

            var phone = $("#phone2").val().replace(/\s/gi, "");
            if (phone == "") {
                alert("חובה למלא טלפון");
                return;
            }

            $.ajax({
                type: "POST",
                cache: false,
                url: "/he/getXML.aspx?sFunc=AskForHelperLesson&obj=MailSender",
                data: "date=" + $("#lessonsdate").val() + "&phone=" + escape(phone) + "&time=" + escape($("#lessonstime").val()),
                dataType: "html",
                success: function(txt) {
                    alert("בקשתך התקבלה במערכת");
                    $("#phone2").val("");
                    $("#helper_lesson").fadeOut("slow");
                }
            });

        },

        OpenDetails: function() {
            $("#popup").find(".helper_lesson").css("display", "block");
        },

        SetCal: function(sCalendarID, iMonth, iYear) {

            $.ajax({
                type: "POST",
                cache: false,
                url: "/he/getStream.aspx?sFunc=GetCal&obj=Students&model=" + (sCalendarID == 'CalendarId2' ? 'Lessons' : 'Events'),
                data: "month=" + iMonth + "&year=" + iYear,
                dataType: "html",
                success: function(txt) {
                    eval("var obj = " + txt);
                    Custom.HP.SetCalendar({
                        ElementID: sCalendarID,
                        StartDay: obj.StartDay - 1,
                        DaysInMonth: obj.DaysInMonth,
                        Month: obj.Month,
                        Year: obj.Year,
                        Events: obj.Events
                    });
                }
            });
        },

        CalendarsGlobal: {}, // Example: {"CalendarId1": {Month:0,Year:2010}
        SetCalendar: function(options) {


            var oFramework = $("#" + options.ElementID).find(".framework:first");
            var oItems = oFramework.children();

            // clean the items
            var bClickable = oFramework.hasClass("clickable");
            oItems.html("");

            if (bClickable)
                oItems.css("cursor", "default");

            // marking days
            var oItemsFiltered = oItems;
            if (options.StartDay > 0)
                oItemsFiltered = oItemsFiltered.filter(":gt(" + (options.StartDay - 1) + ")");

            oItemsFiltered.filter(":lt(" + options.DaysInMonth + ")").each(function(idx) {
                var oEl = $(this);

                oEl.append("<span class=\"time\">" + (idx + 1) + "</span>");
            });

            // marking events
            if (options.Events) {
                jQuery.each(options.Events, function(idx) {
                    var This = this;
                    oItemsFiltered.filter(":eq(" + this.Day + ")").append("<span class=\"strokes\">" + ((function() {

                        var aNames = "One,Two,Three".split(",");
                        var s = "";

                        for (var i = 0; i < aNames.length; i++)
                            s += "<span style=\"width:60px;overflow:hidden;white-space:nowrap;\"" + (This["bDisableHour" + aNames[i]] == "true" ? " class='disabled'" : " class='enabled'") + " obj_info='" + This["object_id"] + "'>" + This["Text" + aNames[i]] + (This["TrainerName" + aNames[i]] != "" ? This["TrainerName" + aNames[i]] : "") + "</span>";
                        return s;

                    })()) + "</span>");
                });
            }

            // marking month
            var aMonths = "ינואר,פברואר,מרץ,אפריל,מאי,יוני,יולי,אוגוסט,ספטמבר,אוקטובר,נובמבר,דצמבר".split(",");
            $("#" + options.ElementID + "Nav").find(".calendarDate:first").text(aMonths[options.Month - 1] + " " + options.Year);

            Custom.HP.CalendarsGlobal[options.ElementID] = {
                Month: options.Month,
                Year: options.Year,
                Events: options.Events
            }
        },

        NextMonth: function(sCalendarID, fFunc) {

            sCalendarID = sCalendarID.replace(/(Nav)$/gi, "");
            var oCalendar = Custom.HP.CalendarsGlobal[sCalendarID];



            if (oCalendar.Month == 12) {
                oCalendar.Month = 1;
                oCalendar.Year++;
            } else {
                oCalendar.Month++;
            }



            fFunc(sCalendarID, oCalendar.Month, oCalendar.Year);

            // TODO: Ajax and call to: Custom.HP.SetCalendar
            // oCalendar.Month
            // oCalendar.Year
        },

        PrevMonth: function(sCalendarID, fFunc) {

            sCalendarID = sCalendarID.replace(/(Nav)$/gi, "");
            var oCalendar = Custom.HP.CalendarsGlobal[sCalendarID];

            if (oCalendar.Month == 1) {
                oCalendar.Month = 12;
                oCalendar.Year--;
            } else {
                oCalendar.Month--;
            }

            fFunc(sCalendarID, oCalendar.Month, oCalendar.Year);

            // TODO: Ajax and call to: Custom.HP.SetCalendar
            // oCalendar.Month
            // oCalendar.Year
        }
    },

    oFlowEl: null,
    iFlowTopBoxes: 648,
    InitFlowBoxes: function() {
        if (!($.browser.msie && parseInt(jQuery.browser.version) == 6) && $("#flowingboxes").length) {

            Custom.oFlowEl = $("#flowingboxes");
            Custom.iFlowTopBoxes = getTop(Custom.oFlowEl.get(0));
            Custom.FlowBoxes();
        }
    },
    FlowBoxes: function() {

        if (screen.height <= 864)
            return;

        $(window).bind("scroll", function() {

            var iBodyTop = document.body.scrollTop * 1 || 0;
            iBodyTop = Math.max(iBodyTop, document.documentElement.scrollTop);

            if (iBodyTop > (Custom.iFlowTopBoxes - 5))
                Custom.oFlowEl.removeClass("FlowingBoxes").addClass("FlowingBoxes");
            else
                Custom.oFlowEl.removeClass("FlowingBoxes");


        });
    },

    PrintCupon: function(oEl) {

        var sLi = getOuterHTML(oEl.tagName == "LI" ? oEl : $(oEl).parents("LI:first").get(0));

        var sCupon = ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\" /><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><link rel=\"StyleSheet\" href=\"/css/general.css\" /><link rel=\"StyleSheet\" href=\"/css/title-box2.css\" /><link rel=\"StyleSheet\" href=\"/css/customer-service.css\" /></head><body style=\"margin:0px;padding:0px;\"><div class=\"site-body\" style=\"border:none;width:auto;margin:0px;padding:0px;\"><div class=\"content\" style=\"width:305px;overflow:hidden;margin:0px;padding:0px;padding-top:5px;\"><div class=\"title-box customer-service\" style=\"float:none;margin:0px;\"><div class=\"box-grey box-grey-first box-grey-last\" style=\"width:305px;\"><div class=\"box-grey-corner-f box-grey-bl-f\"><div class=\"box-grey-corner-f box-grey-br-f\"><div class=\"box-grey-corner box-grey-tl\"></div><div class=\"box-grey-corner box-grey-tr\"></div><ul class=\"lstCustomerService\">" + sLi.replace(/Custom\.PrintCupon\(this\)/gi, "print()") + "</ul><div style=\"height:5px;overflow:hidden;\">&nbsp;</div></div></div></div></div></div></div></body></html>");

        var oWin = open("", "winName", "width=305,height=150");
        oWin.document.write(sCupon);
        oWin.document.close();
    },

    StudentLogin: function() {

        var sIdentityDoc = $("#StudentID").val().replace(/\s/gi, "");
        if (sIdentityDoc == "" || isNaN(sIdentityDoc) || sIdentityDoc.length < 5) {
            alert("תעודת הזהות שהקשת איננה תקנית");
            return;
        }

        location.href = '/he/getStream.aspx?obj=StudentsLogin&sFunc=Login&id=' + sIdentityDoc;
    }
}

onload = function() {
    Custom.InitFlowBoxes();
	$("#lstTopMenu").children(".selected").find("A").each(function() {
		$("#frmContactSitePage").filter(function() {
			return !$(this).hasClass("DontChangeMe");
		}).val($(this).html());
	});
}


