// preload slide menu tab images  
pic1 = new Image(); pic1.src = main_url + '/images/tabs_editor.png';
pic2 = new Image(); pic2.src = main_url + '/images/tabs_recent.png';
pic3 = new Image(); pic3.src = main_url + '/images/tabs_popular.png';

// preload slide menu header images
pic4 = new Image(); pic4.src = main_url + '/images/head_editor.gif';
pic5 = new Image(); pic5.src = main_url + '/images/head_recent.gif';
pic6 = new Image(); pic6.src = main_url + '/images/head_popular.gif';

// preload the section titles in english
pic7 = new Image(); pic7.src = main_url + '/images/sections/action_small_eng.png';
pic8 = new Image(); pic8.src = main_url + '/images/sections/flash_small_eng.png';
pic9 = new Image(); pic9.src = main_url + '/images/sections/tachwich_small_eng.png';
pic10 = new Image(); pic10.src = main_url + '/images/sections/warak_small_eng.png';

var num_pages = 0;

// this controls the maximum width for full-size images displayed on the site
var max_width = 700;

$(document).ready(function(){
	
	// Add 'busy' class when AJAX is in process, to change the cursor, but only
	// if the page is not in the dashboard
	if (!(is_dashboard)) {
		$("html").bind("ajaxStart", function(){
			$(this).addClass('busy');
		}).bind("ajaxStop", function(){
			$(this).removeClass('busy');
		});
	}
	
	// set up the Filament Group buttons
	$(".fg-button:not(.ui-state-disabled)")
		.hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		)
		.mousedown(function(){
				$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
				if ($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')){
					$(this).removeClass("ui-state-active");
				} else { 
					$(this).addClass("ui-state-active");
				}
		})
		.mouseup(function(){
			if (!$(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button')) {
				$(this).removeClass("ui-state-active");
			}
		});

	// set click events for add_media buttons
	$("#add_video_button").click(function() { embeddedvideo_insert(); });
	$("#add_photo_button").click(function() { $("#add_image").click() });
	$("#add_audio_button").click(function() { $("#add_audio").click() });
   	
	//resize the photos on the page
	$(".entry-content img").each(function() {
		resizeImage($(this));
	});
	
	$("#upload_button").click(function() {
		if (logged_in) {
			return true;
		} else {
			alert('Please log in first to upload content, or register for a new account if you do not yet have one.');
			return false;
		}
	});
	
	// if the home_editors choice widget is present, then adjust the positions
	// of the boxes
	if ( ($("#home_editors_choice").length) && ($(".home_box").length) ) {
	
		// stores the current column within the loop
		var current_col = 1;
		
		var home_box_heights = new Array();
		
		// this variable will store the number of pixels we should move the
		// box up and the height of each column
		var move_up1 = 0; var col_height1 = 0;
		var move_up2 = 0; var col_height2 = 0;
		var move_up3 = 0; var col_height3 = 0;
		var margin_top = '';
		var max_col_allowed=2;
		
		$(".home_box").each(function(index) {
			home_box_heights[index] = $(this).height();
			
			margin_top = "-" + eval('move_up' + current_col) + "px";
			
			$(this).css('margin-top', margin_top);
//			$(this).animate({marginTop: margin_top}, 1500);
			
			// if we're at the last column, then calculate the move_up values
			// to be used by the previous row
			if (current_col == max_col_allowed) {
				
				col_height3 += home_box_heights[index];
				col_height2 += home_box_heights[index-1];
				col_height1 += home_box_heights[index-2];
			
				max_height = Math.max(col_height1, col_height2, col_height3);
				move_up3 = max_height - col_height3;
				move_up2 = max_height - col_height2;
				move_up1 = max_height - col_height1;
			}
		
			// set the current_col value to the appropriate value for the previous 
			// iteration of the loop
			current_col++;
			if (current_col == (max_col_allowed)) {
				
				current_col = 1;
			}
				
		// end each loop
		});

		
	}
  	
	if ($("#slide_menu").length) {
		$("#slide_menu").css('top', $("#content").offset().top + 'px');
	}
	$(window).scroll(positionSlideMenu);
	$("#slide_widget").hide();
	$("#slide_widget_wrapper").hide();
	
	$("#slide_menu .close_widget").click(function() {
		$(this).parent().hide("slide", { direction: "left" }, function() {
			$("#slide_widget_wrapper").hide();
		});

		$('#tabs_img').attr('src', main_url + '/images/tabs.png');
	});
	
	// Search for div's with id="content_page_X", where X is an integer, in
	// order to determine the number of pages in the article.
	// This loop can handle a maximum of 50 pages, which should never happen.
	for (var i=1; i<=50; i++) {
		if ($("#content_page_" + i).length) {
			num_pages++;
		} else {
			break;
		}
	}
	
	// Set up the section menu images to switch to English on mouseover
	$("#section_menu img").mouseover(function() {
		var img_src = $(this).attr('src');
		img_src = img_src.replace('.png', '_eng.png');
		$(this).attr('src', img_src);
	}).mouseout(function() {
		var img_src = $(this).attr('src');
		img_src = img_src.replace('_eng.png', '.png');
		$(this).attr('src', img_src);
	});
	
	$("#user_forms").hide();
	$(".user_form").hide();
	
	$("#login_link").click(function() { 
		showUserForm("#login_form"); 
		return false;
	});
	$("#register_link").click(function() {
		showUserForm("#register_form"); 
		return false;
	});
	
	$("#login_button").click(function() { 
		$("#loginform").submit();
	});

	$(document).mouseup(function(e) {
		//if user clicks outside of login or register form, then close the form
		if ( $(e.target).parents("#user_forms").length==0 ) {
			$("#user_forms").hide();
			$(".user_form").hide();
		}
		
		//if user clicks outside of slide menu, close it
		if ( $(e.target).parents("#slide_menu").length==0 ) {
			// but only if it's already open
			if ($("#slide_widget").is(':visible')) {
				$("#slide_menu .close_widget").click();
			}
		}
		
	}); 
	
	$(".user_button").css("width", $("#login_username").css("width"));
	$("#user_rememberme").css("width", $("#login_username").css("width"));

	$("#register_button").click(function() { 
		registerUser();
		return false;
	});
	
	$("#search_button").click(function() {
		$("#searchform").submit();
		return false;
	});
	
	$("#your-profile").addClass('ui-corner-all');
	$("#posts-filter").addClass('ui-corner-all');
	$("input, select").addClass('ui-corner-all');

	// reset the value of the post_category dropdown
	$("#post-body select#post_category").val('');
	
	// if the post being edited is already in a category, then set the dropdown
	// to that category.
	$("#categorychecklist input[type=checkbox]").each(function() {
		if ($(this).attr('checked')) {
			$("#post-body select#post_category").val($(this).val());
		}
		postCategoryChange();
	});
	
//	$("#post-body select#post_category").change(function() {
//		postCategoryChange();
//	});
	
	$("#publish_new").click(function() {
		if ( ( $("#post-body select#post_category").val() == "" ) && $("#post_category").is(":visible") ) {
			alert('please select a category');
			return false;
		} else {
			$("input#publish").click();
			// then unheck all the category checkboxes (these have been hidden)
			$("#categorychecklist input[type=checkbox]").attr('checked', false);
		}
	});
	
	// if the paragraph is arabic, make sure the text goes from right to left
	$("#main p").each(function() {
		if ($(this).css('text-align') == 'right') {
			$(this).attr('dir', 'rtl');
		}
	});
	
	$("#view_all").click(function() {
		$("#search_cat").val(current_category_id);
		$("#s").val(' ');
		$("#searchform").submit();
		return false;
	});
	
	$(".close_issue").click(function() {
		$("#magazine_content_form").hide();
	});

	$("#ads_button").click(function() { 
		advertise();
	});
	$("#sub_button").click(function() { 
		send_subscribtion();
	});
	
	
	if ($("#upload_img_button").length > 0) {
		var post_obj = new Object();
		
		new AjaxUpload('upload_img_button', {
			action: 'wp-admin/kzmz-upload.php',
			type: "POST",
			data: post_obj,
			
			onChange: function() {
				
				
			},
			onSubmit: function() {
				$("#upload_img_button").addClass('ui-state-disabled');
				$("#upload_sub_message").html('<span class="loading">uploading...</span>');
			},
			onComplete: function(file, response) {
				$("#upload_img_button").removeClass('ui-state-disabled');		
				var response_obj = $.parseJSON(response);	
				$("#upload_sub_message").html(parse_response_obj(response_obj));
				
				if ( (typeof response_obj.file_name === 'string') 
				    && (typeof response_obj.post_id !== 'undefined') ) {
					var sub_image_dir=response_obj.image_path;
					$("#sub_img_name").html("<img src='" 
												+ sub_image_dir
												+ "' tag='" 
												+ (response_obj.file_name) 
												+ "' width='250px' />");
				}
				
			
				$("#sub_image_dir").val(sub_image_dir)
			}

		});
	}

}); // end document.ready

function resizeImage(img) {
	var width = $(img).attr('width');
	var height = $(img).attr('height');
	
	var new_width;
	var new_height;
	var scale;
	
	if (width > max_width) {
		scale = max_width / width;
		new_width = width * scale;
		new_height = height * scale;
		
		$(img).attr('width', new_width);
		$(img).attr('height', new_height);
	}
}

function postCategoryChange() {
	var section_name = $("#post-body select option:selected").text();
	section_name = section_name.toLowerCase()
	if (section_name == 'videos') {
		$("#add_video").show();
	} else {
		$("#add_video").hide();
	}
	
	if (section_name == 'audio') {
		$("#add_audio").show();
	} else {
		$("#add_audio").hide();		
	}
}

function positionSlideMenu() {
	if ( !($("#slide_menu").length) ) {
		return;
	}
	var offset = $(document).scrollTop();
	var top = $("#content").position().top;
	var slide_menu_pos;

	// if the window is shorter than the height of the slide menu, keep it at
	// the top to prevent extending it past the bottom of the screen
	if ( (offset < top) || ($("#slide_widget").height() > $(window).height()) ) {
		slide_menu_pos = top;
	} else {
		slide_menu_pos = offset;
	}

	$("#slide_menu").animate({top:slide_menu_pos	 + 'px'},{duration:400,queue:false});
}

function slideMenuSelect(tab) {
	tabs_src = main_url + '/images/tabs_' + tab + '.png'; 
	$('#tabs_img').attr('src', tabs_src);
	
	$("#slide_widget_wrapper").show();
	
	if ($("#slide_" + tab).is(':visible')) {
		$("#slide_menu .close_widget").click();
	} else {
		$('.slide_tab').hide();
		$('#slide_' + tab).show();
			
		if ($("#slide_widget").is(':hidden')) {
			$("#slide_widget").show("slide", { direction: "left" });
		}
	}
}

function showUserForm(form_id) {
	$("#user_forms").hide();
	$(".user_form").hide();

	$(form_id).show();
	$("#user_forms").show();
	
	var offset = parseInt($("#main").offset().left.toString().replace("/px/", ""));

	offset = offset + 160 + "px";
	
	// position the css popup for the user login/registration forms
	$("#user_forms").css("margin-right", offset);

}

function registerUser() { 
	var post_obj = new Object();

	post_obj.target = 'register_user';
	post_obj.user_email = $("#register_email").val();
	post_obj.first_name = $("#register_first_name").val();
	post_obj.last_name = $("#register_last_name").val();
	post_obj.country = $("#register_country").val();

	$.ajax({
		type: "POST",
		url: main_url + "/kzmz-ajax.php",
		data: post_obj,
		beforeSend: function(){
			$('#register_form .status').html('loading...');
		},
		complete: function(){

		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#register_form .status').html('There has been an error with the request. Please try again or contact admin@kazamaza.com');
		},
		success: function(html){
			$('#register_form .status').html(html);
		}
	});

}
/******************* flag post *********************************************************/
function flag_post(post_id){
	var post_obj = new Object();
	post_obj.target = 'flag_post';
	post_obj.post_id = post_id;
	
    if (confirm('Are you sure you want to report this post?') ){
		$.ajax({
			type: "POST",
			url: main_url + "/wp-admin/kz-flag.php",
			data: post_obj,
			beforeSend: function(){
				
			},
			complete: function(){

			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				$('#single_msg').html('There has been an error with the request. Please try again.');
			},
			success: function(html){
				$('#single_msg').html(html);
			}
		});
	}
}
/****************share **********************************************************************/
function fbs_click(u,t) {
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}
function twiter_click(u,t){
window.open('http://twitter.com/home?status= ' + t + "-" +encodeURIComponent(u),'sharer','toolbar=0,status=0,width=626,height=436');
return false;
}

// this function is called whenever a user wants to open RSS from Chrome browser
function alert_chrome_user(url){
	alert ("Please make sure that RSS Extension is installed for Google Chrome. \n You can use the following link https://chrome.google.com/extensions/detail/nlbjncdgjeocebhnmkbbbdekmmmcbfjd");
	window.open(url);
	return;

}

/****************************************** magazine*****************************************************/
//save the old book
var book_width="";
var book_height="";
var book_percent="";
var center_book="";
function goToPage(book_id,position,total){
	// ACCESS VARIABES INSIDE IFRAME
	//alert(document.getElementById('mag_frame').contentWindow['flippingBook1'].pages);
	// get widht and height
	var next= position -1;
	var previous= position +1;
	var next_link="";
	var previous_link="";
	var magazine_page=document.getElementById('mag_frame').contentWindow['flippingBook1'].pages[position].replace("|","");

	var share_links="";
	// Add facebook link
	share_links +="&nbsp;" + "<a title=\"Facebook\" onclick=\"javascript:parent.fbs_click('" + magazine_page + "','"+ page_names[position] +"');\"><img  alt=\"Facebook\" title=\"Facebook\" src=\"http://w.sharethis.com/chicklets/facebook.gif\"></a>";
	// Add twitter link
	share_links +="&nbsp;" + "<a title=\"Twitter\" onclick=\"javascript:parent.twiter_click('"+ magazine_page +"','"+ page_names[position] +"');\"><img  alt=\"Twitterr\" title=\"Twitterr\" src=\"http://w.sharethis.com/chicklets/twitter.gif\"></a>";
	// Add mail link
	share_links +="&nbsp;" + "<a title=\"email\" href=\"mailto:?subject=" + page_names[position] + "&amp;body=" + magazine_page + "\" rel=\"nofollow\"><img style='border:0px' alt=\"email\" title=\"email\" src=\"http://w.sharethis.com/chicklets/email.gif\"></a>";
	
	if (next >= 0){
	
		next_link="<a href=\"javascript:parent.goToPage(" + book_id + ","+next +","+total+"); \">Next </a>";		
	}
	if (previous < total){
		
		previous_link="<a href=\"javascript:parent.goToPage(" + book_id + ","+previous +","+total+"); \">Previous </a>";			
		
	}
	
	if (book_width==""){
		
		book_percent=(document.getElementById('mag_frame').contentWindow['flippingBook1'].settings.autoFlipSize);
		book_width=(document.getElementById('mag_frame').contentWindow['flippingBook1'].settings.bookWidth)/2;
	    book_height=(document.getElementById('mag_frame').contentWindow['flippingBook1'].settings.bookHeight);
		
		//check if center page
		center_book=document.getElementById('mag_frame').contentWindow['flippingBook1'].settings.centerBook;
		
	
	}
	
	if (center_book){
		document.getElementById('mag_frame').contentWindow.document.getElementById("book1").style.textAlign="center";
	}
	document.getElementById('mag_frame').contentWindow.document.getElementById("book1").innerHTML ="<div style='padding-bottom:5px;padding-top:5px;font-size:14px;'><a href='javascript:parent.show_original_mag("+book_id+")'>Cover</a>&nbsp" + next_link +"&nbsp;" + previous_link + "&nbsp;" + share_links;
	document.getElementById('mag_frame').contentWindow.document.getElementById("book1").innerHTML +="</div>";	
	document.getElementById('mag_frame').contentWindow.document.getElementById("book1").innerHTML +="<img  width='"+book_width+"' height='"+book_height+"' style='align:center' src='"+magazine_page+"' />";

	
	$("#magazine_content_form").hide();
	
}

function show_original_mag(book_id){
 
	document.getElementById('mag_frame').src=main_url +"/wp-content/plugins/page-flip-image-gallery/popup.php?book_id="+book_id;

}

function show_issue_content() {
	$("#magazine_content_form").show();
	
	var offset = parseInt($("#single_left_menu").offset().left.toString().replace("/px/", ""));
	
	offset = offset + 800 + "px";
	// position the css popup for the user login/registration forms
	$("#magazine_content_form").css("margin-right", offset);
}
function open_popup(my_url,title){
	//
	newwindow=window.open(my_url,'Printer_Friendly',"location=no,toolbar=no,menubar=no,minimizable=no,dialog=no,fullscreen=yes,scrollbars=yes");
	
	if (window.focus) {newwindow.focus();}	
}

// ########################### Advertise ############################################################################
function advertise(){
	var post_obj = new Object();

	post_obj.target = 'advertise';
	post_obj.ads_username = $("#ads_username").val();
	post_obj.ads_company = $("#ads_company").val();
	post_obj.ads_city = $("#ads_city").val();
	post_obj.ads_telephone = $("#ads_telephone").val();
	post_obj.ads_email = $("#ads_email").val();

	$.ajax({
		type: "POST",
		url: main_url + "/kzmz-ajax.php",
		data: post_obj,
		beforeSend: function(){
			$('#advertise_form .status').html('loading...');
		},
		complete: function(){

		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#advertise_form .status').html('There has been an error with the request. Please try again or contact admin@kazamaza.com');
		},
		success: function(html){
			$('#advertise_form .status').html(html);
		}
	});
}
/**
 * Given a response object, this function returns the message in html,
 * depending on whether the response is an error or not.
 * If a title is supplied, that is used. Otherwise, the defaults of
 * 'Error' or 'Ok' are used.
 */
function parse_response_obj(response_obj) {
	var response_html;

	if (typeof response_obj.error !== 'undefined') {
		if (typeof response_obj.title === 'string') {
			response_html = '<span class="error">' + response_obj.title + '</span> ';
		} else {
			response_html = '<span class="error">ERROR.</span> ';
		}
		response_html += response_obj.error;
	} else {
		if (typeof response_obj.title === 'string') {
			response_html = '<span class="ok">' + response_obj.title + '</span> ';
		} else {
			response_html = '<span class="ok">OK.</span> ';
		}
		response_html += response_obj.message;
	}
	
	return response_html;
}


function send_subscribtion(){
	var post_obj = new Object();

	post_obj.target = 'subscribe';
	post_obj.sub_username = $("#sub_username").val();
	post_obj.sub_company = $("#sub_company").val();
	post_obj.sub_building = $("#sub_building").val();
	post_obj.sub_street = $("#sub_street").val();
	post_obj.sub_nearby = $("#sub_nearby").val();
	post_obj.sub_country = $("#sub_country").val();
	post_obj.sub_mail = $("#sub_mail").val();
	post_obj.sub_phone = $("#sub_phone").val();
	post_obj.sub_ads_text = $("#sub_ads_text").val();
	post_obj.sub_image_dir = $("#sub_image_dir").val();

	$.ajax({
		type: "POST",
		url: main_url + "/kzmz-ajax.php",
		data: post_obj,
		beforeSend: function(){
			$('#sub_form_col .status').html('loading...');
		},
		complete: function(){

		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#sub_form_col .status').html('There has been an error with the request. Please try again or contact admin@kazamaza.com');
		},
		success: function(html){
			if (html.indexOf("<strong>ERROR</strong>") !=-1){
			$('#sub_form_col .status').html(html);
			}else{
				// no error
				$('#sub_form_col').html('<br/>');
				$('#sub_form').html(html);
				
			}
		}
	});

}

function limitChars(textid, limit, infodiv)
{
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit)
	{
		$('#' + infodiv).html('You cannot write more then '+limit+' characters!');
		$('#'+textid).val(text.substr(0,limit));
		return false;

	}else{
			$('#' + infodiv).html('You have '+ (limit - textlength) +' characters left.');
			return true;

	}

}
var subtextlength=0;
function word_count(textid,limit, infodiv ) {

    var number = 0;
   	var text = $('#'+textid).val(); 
    var strText = jQuery.trim($('#' +textid).val());
	
	number= strText.split(/\s+/).length;
	if (text ==""){
	number=0;

	}
	if (number >limit){
		$('#' + infodiv).html('You can\'t write more then '+limit+' words!');
		$('#'+textid).val(text.substr(0,subtextlength));
		return false;
	}else{
		subtextlength = text.length;
		$('#' + infodiv).html('You have '+ (limit - number) +' words left.');
	
	}
}
function PopupCenter(pageURL,title,w,h) {
var left = (screen.width-w)/2;
var top = (screen.height-h)/2;
var page_properties="left="+left+",top="+top+",width="+w+",height="+h+",scrollbars=yes,titlebar=no,location=no,toolbar=no,menubar=no,status=no,addressbar=no, directories=no, copyhistory=no, fullscreen=no";
targetWin = window.open (pageURL,"Newspaper",page_properties );

if (window.focus) {targetWin.focus();}

	


}


