/* B.H. ajax_windows */
var FormsClass = new Class.create();
FormsClass.prototype = {

    initialize: function(main_div_id, content_div_id) {
        this.main_div = $(main_div_id);
        this.content_div = $(content_div_id);
        this.content = "";
        this.redirect_url = "";
        this.must_redirect_onclose = false;
        this.must_redirect_after_register = false;
        this.redirect_url_onclose = "index.php";
        this.send_to_friend_id = -1;
    },
    
    OpenWindow: function(delta_y) {
        var h_pos = screen.availHeight/2-delta_y;
        if(h_pos < 10) h_pos = 10;
        var pp = document.viewport.getScrollOffsets()[1]+h_pos+'px';
        this.content_div.style.top = pp;
        this.main_div.style.height = screen.availHeight + document.viewport.getScrollOffsets()[1]+'px';
        this.main_div.style.display = "";
        document.body.style.overflow = 'hidden';
        /*new Draggable(this.content_div);*/
    },

    CloseForm: function() {
        document.body.style.overflow = 'auto';
        this.main_div.style.display = "none";
        this.content_div.innerHTML = "";
        if(this.must_redirect_onclose) {
            location.replace(this.redirect_url_onclose);
        }
    },
    
    OpenSendToFriendForm: function (id, type) {
        this.GetFormsContent('send_to_friend&type='+type+'&id='+id);
        this.OpenWindow(306);
        this.send_to_friend_id = id;
    },
    
    OpenSendInfoAboutBadMessage: function (id) {
        this.GetFormsContent('send_info_about_bad_message&id='+id);
        this.OpenWindow(306);
        this.send_to_friend_id = id;
    },
    
    // access_type: LIMITED_ACCESS | READONLY
    OpenRequestAccesToForumForm: function (access_type, forum_id) { 
        this.GetFormsContent('request_access_to_forum&access_type='+access_type+"&forum_id="+forum_id);
        this.OpenWindow(300);
    },

    RequestAccesToForumFormSubmit: function() {
        var frm = document.forms['AddRequestAccessMessage'];
        var message = frm.elements['message'].value;
        var operation = frm.elements['operation'].value;
        var forum_id = frm.elements['forum_id'].value;
        var access_type = frm.elements['access_type'].value;
        
        if(message.length == 0) {
            alert("נא תמלא הערות");
            frm.elements['message'].focus();
            return false;
        }
        this.main_div.style.cursor = 'progress';
        
        var SendArray = {};
        SendArray['message'] = message;
        SendArray['operation'] = operation;
        SendArray['forum_id'] = forum_id;
        SendArray['access_type'] = access_type;

        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?form_type=request_access_to_forum&access_type="+access_type, {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                obj.main_div.style.cursor = 'default';
                obj.content_div.innerHTML = transport.responseText;
            }
        });

        return false;
    },
    
    SendInfoAboutBadMessageFormSubmit: function() {
        var frm = document.forms['send_to_moder_bad_message_info'];
        var message = frm.elements['message'].value;
        
        if(message.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא הערות";
            frm.elements['message'].focus();
            return false;
        }
                      
        this.main_div.style.cursor = 'progress';
        
        var SendArray = {};
        SendArray['cause'] = frm.elements['cause'].value;
        SendArray['phone'] = frm.elements['phone'].value;
        SendArray['phone_code'] = frm.elements['phone_code'].value;
        SendArray['message'] = frm.elements['message'].value;
        SendArray['id'] = this.send_to_friend_id; 
        SendArray['operation'] = 'send'; 
        
        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?form_type=send_info_about_bad_message", {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                obj.main_div.style.cursor = 'default';
                obj.content_div.innerHTML = transport.responseText;
            }
        });

        return false;
    },
    
    SendToFriendFormSubmit: function(type) {
        var frm = document.forms['send_to_friend'];
        var r_email = frm.elements['recipient_email'].value;
        var s_email = frm.elements['sender_email'].value;
        var s_name  = frm.elements['sender_name'].value;
        
        if(r_email.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא אי-מייל של חבר";
            frm.elements['recipient_email'].focus();
            return false;
        }
        if(!validateEmailv2(r_email)) {
            $("ajax_form_element_error").innerHTML = "כתובת אי-מייל לא נכונה";
            frm.elements['recipient_email'].focus();
            return false;
        }
        if(s_email.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא אי-מייל שלי";
            frm.elements['sender_email'].focus();
            return false;
        }
        if(!validateEmailv2(s_email)) {
            $("ajax_form_element_error").innerHTML = "כתובת אי-מייל לא נכונה";
            frm.elements['sender_email'].focus();
            return false;
        }
        if(s_name.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא שם שלי";
            frm.elements['sender_name'].focus();
            return false;
        }
        
        this.main_div.style.cursor = 'progress';
        
        var SendArray = {};
        SendArray['recipient_email'] = r_email; 
        SendArray['sender_email'] = s_email; 
        SendArray['sender_name'] = s_name; 
        SendArray['operation'] = 'send'; 
        SendArray['own_message'] = frm.elements['own_message'].value;
        SendArray['id'] = this.send_to_friend_id; 
        
        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?form_type=send_to_friend&type="+type, {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                obj.main_div.style.cursor = 'default';
                obj.content_div.innerHTML = transport.responseText;
            }
        });
        
        return false;
    },

    OpenCommentsNeedSignupForm: function() {
        this.GetFormsContent('comments_need_signup');
        this.OpenWindow(300);
    },
    
    OpenContactUsForm: function() {
        this.GetFormsContent('contact_us')
        this.OpenWindow(500);
    },
    
    ContactUsFormSubmit: function() {
        var frm = document.forms['contact_us_form'];
        var first_name = frm.elements['first_name'].value;
        var phone = frm.elements['phone'].value;
        //var phone_code = frm.elements['phone_code'].value;
        var email = frm.elements['email'].value;
        var message = frm.elements['message'].value;

        if(email.length == 0) {
            $("ajax_form_element_error").innerHTML = 'נא למלא כתובת דוא"ל';
            frm.elements['email'].focus();
            return false;
        }
        if(message.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא למלא תוכן";
            frm.elements['message'].focus();
            return false;
        }

        params = {
        	first_name: first_name, phone: phone, email: email, message: message,
        	operation: frm.elements['operation'].value
        };
        
        new Ajax.Request('ajax_forms_requester.php?form_type=contact_us', {
            method: 'post',
            parameters: params, 
            onSuccess: (function(transport) { 
                this.content_div.innerHTML = transport.responseText;
            }).bind(this),
            onFailure: function(tr) {
        		alert(tr.responseText);
        	}
        });
        
        return false;
    },
    
    OpenLoginForm: function() {
        this.GetFormsContent('login')
        this.OpenWindow(300);

        var obj = this;
        new Ajax.Request('ajax_forms_requester.php?get_login_redirect_url', {
            onSuccess: function(transport) { 
                obj.redirect_url = transport.responseText;
            }
        });
    },

    LoginFormSubmit: function () {
        frm = document.forms['sign_in'];
        name = $F('login_username');
        pass = $F('login_password');
        sign_auto = ($F('login_auto')==1)?1:0;
        
        if(name.length == 0) {
        	jQuery("#ajax_form_element_error").slideUp('slow').
        		html("שם משתמש ריק").slideDown('slow');
            frm.elements['username'].focus();
            return false;
        }
        if(pass.length == 0) {
        	jQuery("#ajax_form_element_error").slideUp('slow').
        		html("אין סיסמה").slideDown('slow');
            frm.elements['password'].focus();
            return false;
        }
        
        this.main_div.style.cursor = 'progress';
        
        new Ajax.Request('mk_ajax_server.php', {
            method: 'get',
            parameters: { op: 'process_login', u: name, p: pass, a: sign_auto }, 
            onComplete: (function(transport) {
                this.main_div.style.cursor = 'default';
                frm = document.forms['sign_in'];
                resp = transport.responseText;
                if (resp == 'sign_in_user_not_found') {
                    jQuery("#ajax_form_element_error").slideUp('slow').
                    	html("משתמש לא נמצא או סיסמה שגויה").slideDown('slow');
                    frm.elements['username'].focus();
                    return false;
                } else if(resp == 'user_not_approved') {
                    this.OpenResendActivationEmailForm();
                    return false;
                } else if(resp == 'ok') {
                	//document.location = (this.redirect_url)?this.redirect_url:document.location;
                	document.location = document.location;
                } else {
                	alert('אירעה שגיאה, אנא נסה שוב!\n\n'+resp);
                	document.location = document.location;
                }
            }).bind(this),
            onFailure: (function (tr) {
            	alert('אירעה שגיאה, אנא נסה שוב!\n'+tr.responseText);
            	document.location = document.location;
            }).bind(this)
        });
        
        return false;
    },
    
    ActivateEmailFormSubmit: function () {
        var frm = document.forms['activate_email'];
        var email = frm.elements['email'].value;
        
        if(email.length == 0) {
            alert("נא תמלא אי-מייל");
            frm.elements['email'].focus();
            return false;
        }
        if(!validateEmailv2(email)) {
            alert("האי-מייל לא תקין. נא תמלא כתובת אי-מייל תקינה");
            frm.elements['email'].focus();
            return false;
        }
        
        SendArray = {};
        SendArray['email'] = email; 
        SendArray['operation'] = 'send_activate_email'; 
        
        this.main_div.style.cursor = 'progress';
        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?form_type=resend_activation_email_form", {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                obj.content_div.innerHTML = transport.responseText;
            }
        });
        
        return false;
    },
    
    OpenResendActivationEmailForm: function () {
        this.GetFormsContent('resend_activation_email_form')
        this.OpenWindow(300);
    },
    
    OpenRegisterForm: function () {
        this.GetFormsContent('register')
        this.OpenWindow(500);
    },
    
    TestUsername: function (text_test_ok, text_test_wrong) {
        var frm = document.forms['register_form'];
        var username = frm.elements['username'].value;
        new Ajax.Request('ajax_forms_requester.php?test_username='+username, {
            method: 'get',
            onSuccess: function(transport) {
                if(transport.responseText == 'ok') {
                    $('test_username_result').innerHTML = text_test_ok;
                    $('test_username_result').style.color = '#00FF00';
                }
                else {
                    $('test_username_result').innerHTML = text_test_wrong;
                    $('test_username_result').style.color = '#FF0000';
                }
            }
        });
    },

    RegisterFormSubmit: function (oper) {
        var frm = document.forms['register_form'];
        var name = frm.elements['username'].value;
        var pass = frm.elements['password'].value;
        var pass1 = frm.elements['password1'].value;
        var email = frm.elements['email'].value;
        
        if(name.length == 0) {
            alert("נא תמלא שם משתמש");
            frm.elements['username'].focus();
            return false;
        }
        if(name.length < 2) {
            alert("בין 2 ל-20 תווים");
            frm.elements['username'].focus();
            return false;
        }
        if(oper=='insert' && pass.length == 0) {
            alert("נא תמלא סיסמה");
            frm.elements['password'].focus();
            return false;
        }
        if(pass.length > 0 && pass.length < 6) {
            alert("בין 6 ל-20 אותיות ו/ או מספרים בלבד");
            frm.elements['password'].focus();
            return false;
        }
        if(pass != pass1) {
            alert("שוב סיסמה");
            frm.elements['password1'].focus();
            return false;
        }
        if(email.length == 0) {
            alert("נא תמלא אי-מייל");
            frm.elements['email'].focus();
            return false;
        }
        if(!validateEmailv2(email)) {
            alert("האי-מייל לא תקין. נא תמלא כתובת אי-מייל תקינה");
            frm.elements['email'].focus();
            return false;
        }
        if(!frm.elements['apply_rules'].checked) {
            alert("אתה חייב להסכים לתנאיים על מנת לסיים את ההרשמה");
            frm.elements['apply_rules'].focus();
            return false;
        }
        
        this.main_div.style.cursor = 'progress';
        
        var SendArray = {};
        SendArray['username'] = name; 
        SendArray['password'] = pass; 
        SendArray['email'] = email; 
        if(oper=='insert'){
            if(frm.elements['sex'][0].checked)
                SendArray['sex'] = 'male'; 
            else
                SendArray['sex'] = 'female'; 
        }
        else {
            SendArray['sex'] = frm.elements['sex'].value; 
        }
        SendArray['birthday_year'] = frm.elements['birthday_year'].value; 
        SendArray['birthday_month'] = frm.elements['birthday_month'].value; 
        SendArray['birthday_day'] = frm.elements['birthday_day'].value; 
        SendArray['birthday_place'] = frm.elements['birthday_place'].value; 
        SendArray['sms'] = frm.elements['sms'].checked; 
        SendArray['phone'] = frm.elements['phone'].value; 
        SendArray['phone_code'] = frm.elements['phone_code'].value; 
        SendArray['subscribe_discount'] = frm.elements['subscribe_discount'].checked; 
        if(frm.elements['country_region'])
            SendArray['country_region'] = frm.elements['country_region'].value; 
        if(frm.elements['about_me'])
            SendArray['about_me'] = frm.elements['about_me'].value; 
        if(frm.elements['my_personal_text'])
            SendArray['my_personal_text'] = frm.elements['my_personal_text'].value; 
        
        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?operation=register", {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                obj.main_div.style.cursor = 'default';
                if(transport.responseText != 'update_ok' && transport.responseText != 'insert_ok') {
                    obj.content_div.innerHTML = transport.responseText;
                    return false;
                }
                else
                    if(transport.responseText == 'insert_ok')
                        obj.ShowMessageAfterRegister();
                    else {
                        if(oper=='update') {
                            location.reload();
                        }
                        else {
                            if(this.must_redirect_after_register)
                                location.replace(this.redirect_url_onclose);
                            else
                                obj.CloseForm();
                        }
                    }
            }
        });

        return false;
    },
    
    ShowMessageAfterRegister: function () {
        this.GetFormsContent('message_after_register')
        this.OpenWindow(450);
    },
    
    ForgotPasswordForm: function () {
        this.GetFormsContent('forgot_pass')
        this.OpenWindow(180);
    },

    ForgotPassFormSubmit: function () {
    },
    
    OpenRedMailForm: function () {
        this.GetFormsContent('red_mail')
        this.OpenWindow(450);
    },
    
    // deprecated
    RedMailFormSubmit: function () {
        var frm = document.forms['red_mail_form'];
        var email = frm.elements['email'].value;
        var title = frm.elements['title'].value;
        var apply_rules = frm.elements['apply_rules'].checked;
        if(email.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא אי-מייל";
            frm.elements['email'].focus();
            return false;
        }
        if(!validateEmailv2(email)) {
            $("ajax_form_element_error").innerHTML = "האי-מייל לא תקין. נא תמלא כתובת אי-מייל תקינה";
            frm.elements['email'].focus();
            return false;
        }
        if(title.length == 0) {
            $("ajax_form_element_error").innerHTML = "נא תמלא כותרת";
            frm.elements['title'].focus();
            return false;
        }
        if(!apply_rules) {
            $("ajax_form_element_error").innerHTML = "אתה חייב להסכים לתנאיים על מנת לסיים את ההרשמה";
            frm.elements['apply_rules'].focus();
            return false;
        }

        frm.target = "file_upload_target";
        frm.action = "ajax_forms_requester.php?operation=add_red_mail";
        return true;
    },

    RedMailFormSubmit_new: function () {
        frm = document.forms['red_mail_form'];
        error_elm = $('redmail_form_element_error');
        op_mode = frm.elements['op_mode'].value;
        email = frm.elements['email'].value;
        title = frm.elements['title'].value;
        apply_rules = frm.elements['apply_rules'].checked;
        if (op_mode!='user') {
        	if(email.length == 0) {
        		error_elm.innerHTML = "נא למלא אי-מייל";
        		frm.elements['email'].focus();
        		return false;
        	}
        	if(!validateEmailv2(email)) {
        		error_elm.innerHTML = "האי-מייל לא תקין. נא למלא כתובת אי-מייל תקינה";
        		frm.elements['email'].focus();
        		return false;
        	}
        }
        if(title.length == 0) {
        	error_elm.innerHTML = "נא למלא כותרת";
            frm.elements['title'].focus();
            return false;
        }
        if(!apply_rules) {
        	error_elm.innerHTML = "יש להסכים עם התנאים לפני שליחת הפניה";
            frm.elements['apply_rules'].focus();
            return false;
        }
        return true;
    },

    RedMailFormSubmit_uc: function () {
        frm = document.forms['red_mail_form_uc'];
        error_elm = $('redmail_uc_form_element_error');
        title = frm.elements['title'].value;
        desc = frm.elements['desc'].value;
        body = frm.elements['body'].value;
        apply_rules = frm.elements['apply_rules'].checked;
        if(title.length == 0) {
        	error_elm.innerHTML = "נא למלא כותרת";
            frm.elements['title'].focus();
            return false;
        }
        if(desc.length == 0) {
        	error_elm.innerHTML = "נא למלא כותרת משנה";
            frm.elements['desc'].focus();
            return false;
        }
        if(body.length == 0) {
        	error_elm.innerHTML = "נא למלא תוכן";
            frm.elements['body'].focus();
            return false;
        }
        if(!apply_rules) {
        	error_elm.innerHTML = "יש להסכים עם התנאים לפני שליחת הכתבה";
            frm.elements['apply_rules'].focus();
            return false;
        }
        return true;
    },

    
    RedMailFormSubmitOk: function() {
        this.CloseForm();
    },
    
    RedMailFormSubmitFileError: function() {
        $("ajax_form_element_error").innerHTML = "";
    },
    
    GetFormsContent: function(type) {
        var obj = this;
        new Ajax.Request('ajax_forms_requester.php?form_type='+type, {
            onSuccess: function(transport) { 
                obj.content_div.innerHTML = transport.responseText;
            }
        });
    },
    
    AddUserToFriend: function(id) {
    	if (!window.site_user_json.id) {
    		this.OpenLoginForm(); return;
    	}
        new Ajax.Request('mk_ajax_server.php', {
            method: 'get',
            parameters: { op: 'add_friend', user_id: id }, 
            onSuccess: function(transport) {
            	resp = transport.responseText;
            	if (resp.length>0) alert(resp);
            },
            onFailure: function(tr) {
            	alert('בעיה בתקשורת. אנא נסה שוב!')
            }
        });
    },
    
    OpenDeleteFriendForm: function(friend_name, user_id) {
        this.GetFormsContent('del_friend&del_friend_name='+friend_name+"&user_id="+user_id);
        this.OpenWindow(300);
    },
    
    DelFriendApply: function(user_id) {
        location.replace('my_account.php?type=my_friends&operation=del_friend&friend_id='+user_id);
    },
    
    AddNewPrivateMessage: function(user_id, url) {
        var SendArray = {};
        SendArray['url'] = url; 
        
        var obj = this;
        new Ajax.Request("ajax_forms_requester.php?operation=add_new_private_message_callback_path", {
            method: 'post',
            parameters: SendArray, 
            onComplete: function(transport) 
            {
                location.replace('my_account.php?type=new_message&user_id='+user_id);
            }
        });
    }
}

/* mk */


function mk_do_nothing() { return; }

// top menu
jQuery(function() {
	var mdata = window.top_menu_data;
	var sel_elm = mdata['menu_l1_sel'];
	var current_color = mdata['current_color'];
    jQuery('a.topm_1').hover(function() {
        if (this.id==sel_elm) return;
        var item = mdata[this.id]; 
        jQuery(this).css({background: 'url('+item[3]+') repeat-x',color: '#ffffff'});
    }, function() {
    	if (this.id==sel_elm) return;
        jQuery(this).css({background: 'none',color: '#000000'});
    });

    var topm2_current = jQuery('a.topm_2_sel');
    jQuery('a.topm_2').hover(function() {
    	jQuery('a.topm_2_sel').removeClass('topm_2_sel').css('background-color', '#e6e6e6');
        jQuery(this).addClass('topm_2_sel').css('background-color', '#'+current_color);
    }, function() {
        jQuery('a.topm_2_sel').removeClass('topm_2_sel').css('background-color', '#e6e6e6');
    	topm2_current.addClass('topm_2_sel').css('background-color', '#'+current_color);
    });
})

function mk_do_logout() {
	new Ajax.Request('/mk_ajax_server.php',{
		parameters: { op: 'logout' }, method: 'get',
		onSuccess: function(tr) {
			res = tr.responseText;
			document.location = document.location;
		},
		onFailure: function(tr) {
			// if we fail to logout by AJAX, let's try an old good way.. ;)
			document.location = "/logout.php";
		}
	});
	return false;
}

window.sel_tb = {
	cont: null,
	last_json: null,
	html_save: null,
	init: function() {
		this.cont = jQuery('#daily_tb_container');
		this.go('init');
	},
	go: function(dir) {
		last_msg_id = this.last_json?this.last_json.msg_id:0;
		this.html_save = this.cont.html();
		this.cont.html('<div style="text-align:center;padding: 20px 0px 30px 0px">'+
    	       '<img src="/images/gallery_new/ajax-loader1.gif" alt="טוען..." />'+
    	       '</div>');
		new Ajax.Request('mk_ajax_server.php',{
			parameters: { op: 'daily_talkback_go', msg_id: last_msg_id, dir: dir }, 
			method: 'get',
			onSuccess: (function(tr) {
				if (!tr.headerJSON) { return; }
				data = tr.headerJSON;
				
				if (data.prev) jQuery('#daily_tb_prev_span').addClass('dtalkback_link_active');
				else jQuery('#daily_tb_prev_span').removeClass('dtalkback_link_active');
				if (data.next) jQuery('#daily_tb_next_span').addClass('dtalkback_link_active');
				else jQuery('#daily_tb_next_span').removeClass('dtalkback_link_active');
				
				if (data.success) {
					this.last_json = data;
					this.cont.hide().html(tr.responseText).slideDown(300);
				} else {
					this.cont.html(this.html_save);
				}
			}).bind(this),
			onFailure: (function(tr){
				this.cont.html(this.html_save);
				alert("Failure!\n"+tr.responseText);
			}).bind(this)
		});
	}
}

function article_vote(art_id,score) {
	new Ajax.Updater('article_votes','/mk_ajax_server.php',{
		parameters: { op: 'article_votes', id: art_id, score: score }, method: 'get',
		onComplete: function(oReq,json) {
			if (!json) { alert('no JSON!'); return; }
			if (json.status=='ok') {
				alert('הצבעתך נקלטה בהצלחה');
			} else if (json.status=='voted') {
				alert('כבר הצבעת על כתבה זו!');
			} else if (json.status=='refresh') {
				// show up nothing, we're just updating HTML
			} else {
				alert('אירעה שגיעה בקליטת ההצבעה. אנו מצטערים, אנא נסו שנית!\n\n'+json.error_msg);
			}
		}
	});
}

function send_password_reminder() {
	email = $F('password_reminder_email');
	if (!email.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
		alert('כתובת דוא"ל אינה תקינה!');
		return;
	}
	new Ajax.Request('/mk_ajax_server.php',{
		parameters: { op: 'password_reminder', email: email }, method: 'get',
		onSuccess: function(tr) {
			res = tr.responseText;
			if (res=='no-such-user') {
				alert('כתובת דוא"ל שהזנת אינה רשומה במערכת! נא לנסות שנית');
				$('password_reminder_email').focus();
			} else if (res=='activation') {
				alert('עדיין לא אימתת את כתובת דוא"ל שלך\n'+
					'קישור לאימות נשלח שוב לכתובת שציינת. תודה');
				document.location = document.location;
			} else if (res=='ok') {
				alert('הסיסמה נשלחה לכתובת דוא"ל שלך. תודה');
				document.location = document.location;
			} else {
				alert('שגיאת התקשרות לשרת\n\n'+res);
			}
		},
		onFailure: function(tr) {
			res = tr.responseText;
			alert('*** שגיאת התקשרות לשרת ***\n'+res);
		}
	});
}

function mk_ensure_login() {
	if (window.site_user_json.id>0) {
		return true;
	}
	forms_class.OpenLoginForm();
	return false;
}

window.affiances_switcher = {
	show_speed: 200,
    active: null,
    active_slider: null,
    show: function(id,slider_elm) {
        new_elm = jQuery('#affiances_details_'+id);
        if (new_elm.size()<1) return;
        if (this.active && (new_elm[0]==this.active[0])) {
            old_elm = this.active;
            this.active_slider.removeClass('affiances_slider_up').addClass('affiances_slider_down');
            this.active = this.active_slider = null;
            old_elm.slideUp(this.show_speed);
            return;
        };
        slider_elm = jQuery(slider_elm);
        if (this.active) {
            old_elm = this.active;
            this.active_slider.removeClass('affiances_slider_up').addClass('affiances_slider_down');
            this.active = new_elm;
            this.active_slider = slider_elm;
            this.active_slider.addClass('affiances_slider_up').removeClass('affiances_slider_down');
            old_elm.slideUp(this.show_speed);
            this.active.slideDown(this.show_speed);
        } else {
            this.active = new_elm;
            this.active.slideDown(this.show_speed);
            this.active_slider = slider_elm;
            this.active_slider.addClass('affiances_slider_up').removeClass('affiances_slider_down');
        }
    }
}

window.htimes_box = {
	current: null,
	current_what: null,
	select: function(what) {
		if (this.current) {
			this.current.removeClassName('gallery_hotbox_header_item_selected');
			jQuery('#htimes_inner_'+this.current_what).hide();
		}
		this.current = $('htimes_box_'+what).addClassName('gallery_hotbox_header_item_selected');
		this.current_what = what;
		jQuery('#htimes_inner_'+what).show();
	},
	init: function() {
		elm = $('htimes_contents');
		if (!elm) return; // no htimes_box in the DOM, give up
		this.select('yom');
		jQuery('#htimes_locs').change((function() {
			$('htimes_contents').innerHTML = '<div style="text-align:center;padding: 20px"><img src="/images/gallery_new/ajax-loader1.gif" alt="טוען..." /></div>';
			loc = $F('htimes_locs');
			new Ajax.Request('/mk_ajax_server.php', {
				parameters: { op: 'htimes_box', loc: loc }, method: 'get',
				onSuccess: (function(tr) {
					res = tr.responseText;
					$('htimes_contents').innerHTML = res; 
					this.select(this.current_what);
				}).bind(this),
				onFailure: function(tr) {
					$('htimes_contents').innerHTML = '<div style="text-align:center;padding: 20px; color: red; font-weight:bold; font-size: 12px">שגיאת התחברות לשרת</div>';
				}
			});
		}).bind(this));
	}
};

// comments

function update_comments_dom() {
	if (window.site_user_json.id) {
	    // user logged in
		jQuery('.comment-username').each(function() {
			this.value = window.site_user_json.username;
		});
		if (window.site_user_json.msg_autoapprove) {
			jQuery(".msg_autoapprove_warning_username").text(window.site_user_json.username+", שימ/י לב!");
			jQuery(".msg_autoapprove_warning").show();
		} 
	}
}

// comreply

function comreply_open(id) {
	var comreply_id = id;
	var comreply_wrapper = jQuery('#comreply_'+id+':hidden');
	if (comreply_wrapper.size()<1) return;
	comreply_wrapper.html('<div class="com_comreply_inner" style="text-align: center">'+
		'<img src="/images/jumbo_banner_close.gif" width="16" height="16" alt="סגור" '+
		'style="float: right; margin: 2px; cursor: pointer" '+
		'onclick="comreply_close('+id+')" />'+
		'<img src="/images/gallery_new/ajax-loader1.gif" alt="טוען..." /><br />'+
		'טוען...</div>').slideDown(500).data('shown',true);
	jQuery.ajax({type: 'GET', url: '/mk_ajax_server.php', 
		data: {op: 'com_comreply', id: id}, dataType: 'html',
		success: function(data, status) {
			comreply_wrapper.html(data);
			update_comments_dom();
		},
		error: function(resp) {
			alert("שגיאה\n"+resp.responseText);
			comreply_close(comreply_id);
		}
	});
}

function comreply_close(id) {
	var comreply_wrapper = jQuery('#comreply_'+id+'');
	if (!comreply_wrapper.data('shown')) return;
	comreply_wrapper.slideUp(500).data('shown',false);
}

function comreply_submit(frm) {
	var data = {
		type: frm.type.value,
		origin_id: parseInt(frm.origin_id.value),
		parent_id: parseInt(frm.parent_id.value),
	    header: frm.header.value, name: frm.name.value, location: frm.location.value,
	    message_body: frm.message_body.value
	};
	var parent_id = data.parent_id;
	if (data.name=='') {
		frm.name.focus();
		alert('שם הוא שדה חובה');
		return false;
	}
	if (data.header=='') {
		frm.header.focus();
		alert('נושא הוא שדה חובה');
		return false;
	}
	jQuery('#comreply_'+parent_id).slideUp('slow');
	jQuery.ajax({type: 'POST', url: '/mk_ajax_server.php?op=com_comreply_post', 
		data: data, dataType: 'html',
		success: function(data, status) {
			comreply_showmsg(parent_id,data);
		},
		error: function(resp) {
			alert("שגיאה\n"+resp.responseText);
			comreply_close(comreply_id);
		}
	});
	return false;
}

function comreply_showmsg(id,msg) {
	var comreply_wrapper = jQuery('#comreply_'+id).hide();
	comreply_wrapper.html('<div class="com_comreply_inner" '+
			'style="text-align: center; font-size:12px; color: red; font-weight: bold">'+
			'<img src="/images/jumbo_banner_close.gif" width="16" height="16" alt="סגור" '+
			'style="float: right; margin: 2px; cursor: pointer" '+
			'onclick="comreply_close('+id+')" />'+
			'<div style="padding: 20px">'+
			msg+
			'</div></div>').slideDown(500).data('shown',true);
}

// Effectively, disable animations on IE. jQuery effects on IE work too much slowly
if (!jQuery.support.opacity) jQuery.fx.off = true;

// Some init actions, called on DomReady by jQuery
jQuery(function() {
	window.sel_tb.init();
	window.htimes_box.init();
	update_comments_dom();
});

/* B.H articles category view specific functions */

CurrencyBox = Class.create({
	initialize: function(tabs,tab_params,curr,cont_id) {
		this.tabs = tabs;
		this.tab_params = tab_params;
		this.current_idx = curr;
		this.content_id = cont_id;
		this.updater = null;
	},
	init: function() {
		box = this;
		this.tabs.each(function(t_id,t_idx) {
			//alert(t_id);
			$(t_id).observe('click',box.tab_clicked.bindAsEventListener(box,t_idx));
		});
		this.update_current(this.current_idx);
	},
	tab_clicked: function(e,idx) {
		this.update_current(idx);
	},
	update_current: function(idx) {
		this.tabs.each(function(t_id,t_idx){
			if (t_idx==idx) $(t_id).addClassName("tselected_e");
			else $(t_id).removeClassName("tselected_e");
		})
		this.updater = new Ajax.PeriodicalUpdater(this.content_id,"mk_ajax_server.php",{
			parameters: this.tab_params[idx], method: 'get', frequency: 15
		});
	}
});

/* B.H. mk/hallery_hotbox.js */

window.ghotbox = {
	cat_id: -1,
	art_id: -1,
	current: null,
	select: function(what) {
		//alert(what);
		elm = $('gallery_hotbox_container');
		elm.innerHTML = '<div style="text-align:center;padding: 20px"><img src="/images/gallery_new/ajax-loader1.gif" alt="טוען..." /></div>';
		if (this.current) this.current.removeClassName('gallery_hotbox_header_item_selected');
		this.current = $('gallery_hotbox_'+what).addClassName('gallery_hotbox_header_item_selected');
		
		new Ajax.Updater('gallery_hotbox_container', '/mk_ajax_server.php',{
			method: 'get',
			parameters: { op: 'gallery_hotbox', cat_id: this.cat_id, art_id: this.art_id, what: what }
		}); 
	}
};

function go(url,is_popup) {
	var p = (is_popup=='')?false:true;
	if (!p) document.location = url;
	else {
		window.open(url);
	}
}

/* images slide show (jQuery plugin) */

(function($) {
	$.fn.kikar_show = function(settings) {
		var config = {fade_speed: 500, delay: 2000};
		if (settings) jQuery.extend(config, settings);
		if (!config.start_delay) config.start_delay = config.delay;

		var process_elm = function() {

			var wrapper = $(this);
			wrapper.css({position: 'relative',
				overflow: 'hidden', width: wrapper.width()+'px',height: wrapper.height()+'px' });
			var div = wrapper.children('.images_show_block');
			var imgs = div.children('img').css({ opacity: 0,position: 'absolute',
				top: '0px', left: '0px' });
			div.css({position:'absolute',top: '0px', left: '0px',display: 'block'});
			if (imgs.size()<2) return;
			var wait_int = null;
			var show_img_func = function(prev,next) {
				clearInterval(wait_int);
				$(imgs[prev]).animate({opacity:0},config.fade_speed);
				$(imgs[next]).animate({opacity:1},config.fade_speed,function() {
					wait_int = setInterval(function() {
						clearInterval(wait_int);
						var new_next = next+1;
						if (new_next>=imgs.size()) new_next = 0;
						show_img_func(next,new_next);
					},config.delay);
				});
			}
			wait_int = setInterval(function(){show_img_func(0,1)}, config.start_delay);
		}
		this.each(process_elm);
		return this;
	};
	
	$.fn.mk_offset = function() {
		var res = {left:0,top:0};
		if (this.size()<1) return res;
		var elm = this[0];
		while (elm) {
			res.left += elm.offsetLeft; res.top += elm.offsetTop;
			elm = elm.offsetParent;
		}
		return res;
	};
	
	$.fn.mk_dropdown = function(settings) {
		if (this.size()<1) return this;
		var config = {showFunc: 'fadeIn', hideFunc: 'fadeOut', speed: 'fast', zindex: 500000, 
			width: null, rtl: false, shade: false,
			onshow: null, onhide: null};
		if (settings) jQuery.extend(config, settings);
		if (!config.anchor) return this;
		var subj = this;
		var old_bgdiv = $('#__mk_dropdown_bgdiv');
		if (old_bgdiv) {
			var old_bgdiv_close = old_bgdiv.data('dropdown_close');
			if (old_bgdiv_close) old_bgdiv_close();
		}
		
		// create a "background" div on top the whole document to intercept clicks
		var bgdiv = document.createElement('DIV');
		bgdiv.id = "__mk_dropdown_bgdiv";
		$.each({position: 'absolute', display: 'block', top: '0px', left: '0px',
			width: document.body.offsetWidth+'px', height: document.body.offsetHeight+'px', 
			zIndex: config.zindex},
			function(k,v) {bgdiv.style[k] = v;} );
		document.body.appendChild(bgdiv);
		var hide_handler = function(e) {
			if (e) e.stopPropagation();
			document.body.removeChild(bgdiv[0]);
			subj.data('dropdown_close',null);
			subj[config.hideFunc](config.speed,function() { if (config.onhide) config.onhide.call(subj); });
			return false;
		};
		bgdiv = $(bgdiv).click(hide_handler);
		if (config.shade) bgdiv.css({backgroundColor: '#000000',opacity: 0.2});
		subj.data('dropdown_close', hide_handler);
		bgdiv.data('dropdown_close', hide_handler);
		
		var a = $(config.anchor);
		if (!config.width) config.width = this.outerWidth();
		var off = a.mk_offset();
		off.top += a.outerHeight();
		if (config.rtl) off.left += (a.outerWidth()-config.width);
		this.hide().css({position: 'absolute', left: off.left,top: off.top, zIndex: config.zindex+1})
			[config.showFunc](config.speed,function(){ if (config.onshow) config.onshow.call(subj); });
		return this;
	};
})(jQuery);

/*
		if ($.browser.msie && (parseInt($.browser.version)>10)) {
			var get_left_offset = function(elm) {
				if (!elm) return 0;
				return elm.offsetLeft + get_left_offset(elm.offsetParent);
			}
			var off = a.offset();
			off.left = get_left_offset(a[0]);
			off.top += a.outerHeight();
			if (config.rtl && config.width) off.left += (a.outerWidth()-config.width);
		} else {

*/