var STATIC_FOLDER = "http://getapp.development.co.il/";

$(function() {
	$("#main_bar #cats li.menuTrigger").hoverIntent({
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
		interval: 100, // number = milliseconds for onMouseOver polling interval    
		over: function () { // function = onMouseOver callback (REQUIRED)    
			$(this).find("ul").show();
		},
		timeout: 500, // number = milliseconds delay before onMouseOut    
		out: function () { // function = onMouseOut callback (REQUIRED)  
			$(this).find("ul").hide();
		} 
	});
	
	$("#sharing li").hoverIntent({
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
		interval: 100, // number = milliseconds for onMouseOver polling interval    
		over: function () { // function = onMouseOver callback (REQUIRED)    
			$(this).find(".tooltip").show();
		},
		timeout: 100, // number = milliseconds delay before onMouseOut    
		out: function () { // function = onMouseOut callback (REQUIRED)  
			$(this).find(".tooltip").hide();
		} 
	});
});

var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}

function is_email(str) {
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(str);
}

function is_phone(str) {
	return /^([0-9_\.\-\+])+$/.test(str);
}

function addToBookmarks(link) {
	var url = "http://www.getapp.co.il";
	var title = "GetApp - אפליקציות ומשחקים לסלולרי שלך";
	
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
		return;
	}
	if(window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
		return;
	}
	
	alert("נראה שהדפדפן שלך איננו תומך בהוספת מועדפים אוטומטית.\r\n"+
		"תוכל להוסיף את GetApp למועדפים באופן עצמאי:\r\n"+
		"	בחר בתפריט הראשי של הדפדפן את \"מועדפים\" ולאחר מכן בחר באפשרות \"הוסף דף זה למועדפים\".");
}

//////////// previews ////////////////////

function PreviewImg_resize() {
	var container = $(".big_app_container .visual .pics .pics_container");
	var img = container.find("img.current");
	
	if(img.width() > img.height()) {
		if(img.width() > container.width())
			img.attr("width", container.width());
		else if(img.height() > container.height())
			img.attr("height", container.height());
	} else {
		if(img.height() > container.height())
			img.attr("height", container.height());
		else if(img.width() > container.width())
			img.attr("width", container.width());
	}
}

function PreviewsImg_next() {
	_PreviewsImg_update(true);
}

function PreviewsImg_prev() {
	_PreviewsImg_update(false);
}

function _PreviewsImg_update(isNext) {
	var pics = $(".big_app_container .visual .pics .pics_container");
	var last = pics.find("img.current");
	var pic;
	
	if(isNext)
		pic = last.next("img");
	else
		pic = last.prev("img");
		
	if(pic.size() == 0)
		return false;
	
	last.addClass("hidden").removeClass("current");
	pic.addClass("current").removeClass("hidden");
	
	var nav = $(".big_app_container .visual .pics .nav_container");
	
	if(pic.next("img").size() < 1)
		nav.find(".next").addClass("next_disabled").removeClass("next");
	else
		nav.find(".next_disabled").addClass("next").removeClass("next_disabled");
	
	if(pic.prev("img").size() < 1)
		nav.find(".prev").addClass("prev_disabled").removeClass("prev");
	else
		nav.find(".prev_disabled").addClass("prev").removeClass("prev_disabled");
	
	PreviewImg_resize();
	return pic;
}

///////////// RankIt //////////////////
var rankIt_curr = null;
var rankIt_obj = null;
var rankIt_url = null;
var rankIt_rate = null;

function rankIt_init(rank, url) {
	rankIt_curr = rank;
	rankIt_obj = $(".big_app_container .rankIt");
	rankIt_url = url;
	
	rankIt_obj.mousemove(function (e) {
		var padLeft = 14, padRight = 2;
		var pos = e.pageX - rankIt_obj.position().left - padLeft;
		var width = rankIt_obj.width() - padLeft - padRight;
		var slice = width / 5;
		
		if(pos < 0 || pos > width) {
			rankIt_set(rank);
			return;
		}
		
		rankIt_set(parseInt(pos/slice)+1);
	});
	
	rankIt_obj.mouseout(function(e) {
		rankIt_set(rank);
	});
	
	rankIt_obj.click(function(e) {
		if(rankIt_curr < 1 || rankIt_curr > 5)
			return;
		
		var rate = rankIt_curr; // save it if the rating takes time
		
		$.post(rankIt_url, {rank: rate}, function(data) {
			if(data.status == 0) {
				rankIt_rate = rate;
				rankIt_set(rankIt_rate);
				
				rankIt_obj.unbind('click');
				rankIt_obj.unbind('mouseout');
				rankIt_obj.unbind('mousemove');
				
				rankIt_obj.fadeOut(function() {
					rankIt_obj.fadeIn();
				})
			}
		}, "json");
	});
}

function rankIt_set(rank) {
	if(rankIt_curr != null) {
		if(rankIt_curr == rank)
			return;
		
		rankIt_obj.removeClass("rank"+rankIt_curr);
	}
	rankIt_curr = rank;
	rankIt_obj.addClass("rank"+rankIt_curr);
}


///////////////// lightbox ////////////////////

var lightbox_url = null;

function lightbox_load(url) {
	lightbox_url = url;
	
	$.ajax({
		url: url,
		cache: false,
		success: function(data){
			try {
			_lightbox_setHtml(data);
			} catch(err) {
				  txt="There was an error on this page.\n\n";
				  txt+="Error description: " + err.description + "\n\n";
				  txt+="Click OK to continue.\n\n";
				  alert(txt);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("Ajax error: "+textStatus+" "+errorThrown);
		}
	});
//	$.get(url, {}, function(data) {
//		_lightbox_setHtml(data);
//	}, 'html');
}

function _lightbox_setHtml(html) {
	$("#lightbox").replaceWith(html).show();
		
	var box = $("#lightbox .lightbox");
	var p = ($("body").width() - box.width()) / 2;
	box.css("left", p);
}

function lightbox_close() {
	$("#lightbox").hide();
}

function lightbox_onForm(form, validateFunc) {
	$(form).ajaxForm({
		beforeSubmit: function () {
			return validateFunc($(form));
		},
		success: function (data) {
			_lightbox_setHtml(data);
		}
	});
}



/////////////////// choose phone ///////////////

function choosePhone_platform(platId) {
	if($("#choose_phone #platform #cpPlatform"+platId).hasClass("selected"))
		return;
	
	$.get(lightbox_url+"/"+platId, {}, function(data) {
		$("#choose_phone #phone").remove();
		$("#choose_phone #model").replaceWith(data);
	}, 'html');
	
	$("#choose_phone #platform ul li.selected").removeClass("selected");
	$("#choose_phone #platform #cpPlatform"+platId).addClass("selected");
}

function choosePhone_device(platId, devId) {
	if($("platId #cpDevice"+devId).hasClass("selected"))
		return;
	
	$.get(lightbox_url+"/"+platId+"/"+devId, {}, function(data) {
		$("#choose_phone #phone").replaceWith(data);
	}, 'html');
	
	$("#choose_phone #model ul li.selected").removeClass("selected");
	$("#choose_phone #model #cpDevice"+devId).addClass("selected");
}

var chDevRef = "";



///////////////// Replies //////////////////

function replySubmit_isVaild(form) {
	var error = null;
	
	var name = $(form).find("input[name=name]").val();
	var email = $(form).find("input[name=email]").val();
	var website = $(form).find("input[name=website]").val();
	var content = $(form).find("textarea[name=content]").val();
	var isFollow = $(form).find("input[name=is_follow]:checked").size() == 1;
	
	if(!name || !replySubmit_isName(name))
		error = "חובה לציין שם";
	else if(!email)
		error = "חובה לציין אימייל";
	else if(email && !is_email(email))
		error = "כתובת האימייל אינה חוקית";
	else if(website && !replySubmit_isWebsite(website))
		error = "כתובת האתר איננה חוקית";
	else if(!content)
		error = "חובה להזין תוכן לתגובה";
	else if(isFollow && !email)
		error = "אנא הזן אימייל לשליחת התגובות";
	
	if(error != null) {
		alert("שגיאה: " + error);
		return false;
	}
	return true;
}

function replySubmit_isName(str) {
	return /[a-zA-Zא-ת]{2,}/.test(str);
}

function replySubmit_isWebsite(str) {
	var RegExp = /^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
	if(RegExp.test(str)){
		return true;
	}else{
		return false;
	} 
}

function replies_loadPage(appId, platId, page) {
	$(".big_app_container .comments").fadeOut();
	$.get("/app/replies/appId/"+appId+"/platId/"+platId+"/page/"+page, function(data) {
		
		$(".big_app_container .comments").replaceWith(data);
		$(".big_app_container .comments").fadeIn();
		window.location.hash="replies"; // go to #replies
	
	}, 'html');
}


/////////////// Download ////////////////

function downloadSubmit_isVaild(form) {
	var error = null;
	
	var email = $(form).find("input[name=email]").val();
	
	if(!email)
		error = "יש למלא כתובת דוא\"ל";
	else if(!is_email(email))
		error = "כתובת האימייל אינה חוקית";
	
	if(error != null) {
		alert("שגיאה: " + error);
		return false;
	}
	return true;
}


//////////////// Share ////////////////

function shareSubmit_isVaild(form) {
	var error = null;
	
	var name = $(form).find("input[name=name]").val();
	var email = $(form).find("input[name=mail]").val();
	var to1 = $(form).find("input[name=to1]").val();
	var to2 = $(form).find("input[name=to2]").val();
	var to3 = $(form).find("input[name=to3]").val();
	
	if(!name || !replySubmit_isName(name))
		error = "חובה לציין שם";
	else if(!email || !is_email(email))
		error = "כתובת האימייל אינה חוקית";
	else if((to1 && !is_email(to1)) || (to2 && !is_email(to2)) || (to3 && !is_email(to3)))
		error = "הכתובות למשלוח אינן חוקיות";
	else if(!to1 && !to2 && !to3)
		error = "לא צויינה כתובת למשלוח";
	
	if(error != null) {
		alert("שגיאה: " + error);
		return false;
	}
	return true;
}


//////////////// Contact ////////////////

function contactSubmit_isVaild(form) {
	var error = null;
	
	var name = $(form).find("input[name=name]").val();
	var email = $(form).find("input[name=mail]").val();
	var phone = $(form).find("input[name=phone]").val();
	var msg = $(form).find("textarea[name=msg]").val();
	
	if(!name || !replySubmit_isName(name))
		error = "חובה לציין שם";
	else if(!email || !is_email(email))
		error = "כתובת האימייל אינה חוקית";
	else if(phone && !is_phone(phone))
		error = "מספר הטלפון איננו חוקי";
	else if(!msg)
		error = "נא למלא את תוכן ההודעה";
	
	if(error != null) {
		alert("שגיאה: " + error);
		return false;
	}
	return true;
}


/////////////// Newsletter ////////////////

function newsletterSubmit_isVaild(form) {
	var error = null;
	
	var email = $(form).find("input[name=email]").val();
	var platforms = $(form).find("input[name=platforms[]]:checked");
	
	if(!email)
		error = "יש למלא כתובת דוא\"ל";
	else if(!is_email(email))
		error = "כתובת האימייל אינה חוקית";
	else if(platforms.size() < 1)
		error = "חובה לבחור לפחות פלטפורמה אחת";
	
	if(error != null) {
		alert("שגיאה: " + error);
		return false;
	}
	return true;
}

//////////////////////////////////////////////////

function brokenLink(url, th) {
	if($(th).hasClass('done'))
		return;
	
	$(th).addClass('done');
	
	$.ajax({
		url: '/user/broken_link',
		type: 'POST',
		data: {url: url},
		cache: false,
		success: function(data){
			$(th).html('תודה!');
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			$(th).removeClass('done');
		}
	});
}