// <![CDATA[

// on DOM ready, let the magic begin
$(document).ready(function(){

	// thumbnail hover
	var offsetX = 50;
	var offsetY = -200;

	// load hover for thumbnails
	$("#screenshotsList a").hover(function(e) {
		var href = $(this).attr('href');
		$("#zoomer").html('<img id="largeImage" src="' + href + '" alt="big image" height=\"480px\" />')
		.css('top', e.pageY + offsetY)
		.css('left', e.pageX + offsetX);
		$("#zoomer").show("fast");
	}, function() {
		$('#zoomer').hide();
		$('#zoomer').html("");
	}).click(function(){
		return false;
	});
	
	$("#screenshotsList a").mousemove(function(e) {
		$("#zoomer").css('top', e.pageY + offsetY).css('left', e.pageX + offsetX);
	});

	// functin which makes sure that not too many
	// app windows are open (like settings, file lists, etc.)
	// keeps them at one at a time
	function closeOtherOptions(id,leaveThis){
		if(id == '' || leaveThis == '') return;
		
		if($("#applyDiv-"+id).is(":visible") && leaveThis != 'applyDiv'){
			$("#applyDiv-"+id).hide();
		}
		
		if($("#filesDiv-"+id).is(":visible") && leaveThis != 'filesDiv'){
			$("#filesDiv-"+id).hide();
		}	
	}
	
	// target search key up
	$("#app_search").keyup(function(){
		if(this.value.length == 0){
			$("#searchStatus").removeClass("checkNotOK");
			$("#searchStatus").html('');
			$("#allAppsDiv").html('<h2>No apps have been found matching your search criteria...</h2>');
			$("#allAppsDiv").hide();
			$("#allAppsDivOriginal").show();
			return;
		}
		if(this.value.length < 4){
			$("#allAppsDivOriginal").hide();
			$("#allAppsDiv").show();
			$("#searchStatus").addClass("checkNotOK");
			$("#searchStatus").html('Minimum 4 characters...');
			$("#allAppsDiv").html('<h2>No apps have been found matching your search criteria...</h2>');
			return;
		}else{
			$("#allAppsDivOriginal").hide();
			$("#allAppsDiv").show();
			$("#searchStatus").removeClass("checkNotOK");
			$("#searchStatus").html('');

			$("#searchStatus").addClass("simpleAjaxLoader");
			$.ajax({
				type: "POST",
				url: "ajax_search_app.php",
				data: "q=" + this.value,
				success: function(ajaxResponse){
					switch(ajaxResponse){
						case "FAILED":
							alert('ERROR: Can\'t do it ... :(');
							$("#searchStatus").removeClass("simpleAjaxLoader");
						break;
						case "NOT FOUND":
							$("#searchStatus").removeClass("simpleAjaxLoader");
							$("#allAppsDiv").html('<h2>No apps have been found matching your search criteria...</h2>');
						break;
						default: // everything is most likely OK
							$("#searchStatus").removeClass("simpleAjaxLoader");
							$("#allAppsDiv").html(ajaxResponse);
						break;
					}
				}
			});
		}
	});
	// target search options click
	$("#moreSearchOptions").click(function(){
		if($("#moreSearchOptions").text() == "more options")
			$("#moreSearchOptions").text("less options");
		else
			$("#moreSearchOptions").text("more options");
		
		$("#searchOptionsDiv").toggle();
		return false;
	});

	// target all testers clicks
	$("[id*=showIncentive-]").click(function(){
		var splitId = this.id.split('-');
		if($("#showIncentive-"+splitId[1]).text() == "more info")
			$("#showIncentive-"+splitId[1]).text("less info");
		else
			$("#showIncentive-"+splitId[1]).text("more info");
		$("#incentiveInfo-"+splitId[1]).toggle('fast');
		return false;
	});
	
	var targetOffset = 0;
	// target all testers clicks
	$("[id*=apply-]").click(function(){
		var splitId = this.id.split('-');
		$("#applyDiv-"+splitId[1]).toggle();
				
		$("#applyDiv-"+splitId[1]).addClass("simpleAjaxLoader");
		$.ajax({
			type: "POST",
			url: "ajax_get_apply_form.php",
			data: "q=" + splitId[1],
			success: function(ajaxResponse){
				switch(ajaxResponse){
					case "FAILED":
						alert('ERROR: Can\'t do it ... :(');
					break;
					default: // everything is most likely OK 
						$("#applyDiv-"+splitId[1]).removeClass("simpleAjaxLoader");
						$("#applyDiv-"+splitId[1]).html(ajaxResponse);
					break;
					
				}
			}
		});
		return false;
		
	});
	
	// target all activate clicks
	$("[id*=files-]").click(function(){
		var splitId = this.id.split('-');
		
		closeOtherOptions(splitId[1],'filesDiv');
		
		if($("#filesDiv-"+splitId[1]).is(":visible")){
			$("#filesDiv-"+splitId[1]).html('');
			$("#filesDiv-"+splitId[1]).hide();
			$("#filesText-"+splitId[1]).text("view screenshots");
			return false;
		}else{
			$("#filesText-"+splitId[1]).text("hide screenshots");
		}
		
		$("#filesDiv-"+splitId[1]).show();
		$("#filesDiv-"+splitId[1]).addClass("simpleAjaxLoader");
		$.ajax({
			type: "POST",
			url: "ajax_get_files.php",
			data: "q=" + splitId[1],
			success: function(ajaxResponse){
				$("#filesDiv-"+splitId[1]).removeClass("simpleAjaxLoader");
				switch(ajaxResponse){
					case "FAILED":
						alert('ERROR: Can\'t do it ... :(');
					break;
					default: // everything is most likely OK
						$("#filesDiv-"+splitId[1]).html(ajaxResponse);
						
					break;
					
				}
			}
		});
		return false;
	});

	function updateReportLinks(){
		
		$("[id*=openReport-]").click(function(){
			return false;								  
		});
		
		// target all report clicks
		$("[id*=openReport-]").click(function(){
			var splitId = this.id.split('-');
			$("#reportInfoRow-"+splitId[1]+"-"+splitId[2]).toggle();
			$("#reportInfoStatus-"+splitId[1]+"-"+splitId[2]).addClass("simpleAjaxLoader");
				$.ajax({
					type: "POST",
					url: "ajax_get_report_replies.php",
					data: "q=" + splitId[2],
					success: function(ajaxResponse){
						$("#reportInfoStatus-"+splitId[1]+"-"+splitId[2]).removeClass("simpleAjaxLoader");
						switch(ajaxResponse){
							case "FAILED":
								alert('ERROR: Can\'t do it ... :(');
							break;
							default: // everything is most likely OK
								$("#reportInfo-"+splitId[1]+"-"+splitId[2]).html(ajaxResponse);
								$("#reportInfo-"+splitId[1]+"-"+splitId[2]).toggle('fast');
								
								$("#replyClick-"+splitId[1]+"-"+splitId[2]).click(function(){ return false; });
								
								$("#replyClick-"+splitId[1]+"-"+splitId[2]).click(function(){
									$("#reportReply-"+splitId[1]+"-"+splitId[2]).toggle('fast');
									if($("#replyText-"+splitId[1]+"-"+splitId[2]).text() == "reply")
										$("#replyText-"+splitId[1]+"-"+splitId[2]).text("reply"); // this was cancel reply
									else
										$("#replyText-"+splitId[1]+"-"+splitId[2]).text("reply");
									return false;
								});
								
								/* TODO this gets over initialized
								$("[id*=reportAnswer-]").click(function(){ return false; });
								
								$("[id*=reportAnswer-]").click(function(){
									var splitId2 = this.id.split('-');
									$("#reportAnswerOptions-"+splitId2[1]+"-"+splitId2[2]).toggle('fast');
								}).mouseover(function(){
									$(this).addClass("reportMessageHover");
								}).mouseout(function(){
									$(this).removeClass("reportMessageHover");
								});
								
								*/
								
								$("[id*=deleteReport-]").click(function(){ return false; });
								
								$("[id*=deleteReport-]").click(function(){
									var splitId2 = this.id.split('-');
									
									if(confirm('Delete this reply?\n\nIf this is not the last reply in this thread, it may break \nthe chain of \'thought\' if someone has already answered to it...')){
										var tmp = $("#reportAnswerOptions-"+splitId[1]+"-"+splitId2[2]).html();
										$("#reportAnswerOptions-"+splitId[1]+"-"+splitId2[2]).html("")
										$("#reportAnswerOptions-"+splitId[1]+"-"+splitId2[2]).addClass("simpleAjaxLoader");
										
										$.ajax({
											type: "POST",
											url: "ajax_delete_report.php",
											data: "q=" + splitId2[2],
											success: function(ajaxResponse){
											$("#reportAnswerOptions-"+splitId[1]+"-"+splitId2[2]).removeClass("simpleAjaxLoader");
												switch(ajaxResponse){
													case "FAILED":
														alert('ERROR: Can\'t do it ... :(');
														 $("#reportAnswerOptions-"+splitId[1]+"-"+splitId2[2]).html(tmp);
													break;
													default: // everything is most likely OK
														$("#reportAnswer-"+splitId[1]+"-"+splitId2[2]).remove();
													break;
													
												}
											}
										});
									}// end confirm
									
									return false;
								});
								
								$("#submitReply-"+splitId[1]+"-"+splitId[2]).click(function(){ return false; });
								
								$("#submitReply-"+splitId[1]+"-"+splitId[2]).click(function(){
									if($("#replyMessage-"+splitId[1]+"-"+splitId[2]).val() == '' || $("#replyMessage-"+splitId[1]+"-"+splitId[2]).val() == 'undefined'){
										alert('Please enter your message');
									}else{
										$("#submitReplyStatus-"+splitId[1]+"-"+splitId[2]).addClass("simpleAjaxLoader");
										$("#submitReply-"+splitId[1]+"-"+splitId[2]).attr("disabled", "disabled");
										
										$.ajax({
											type: "POST",
											url: "ajax_send_answer.php",
											data: "q=" + splitId[1] + '&in_reply_to=' + splitId[2] + '&message=' + $("#replyMessage-"+splitId[1]+"-"+splitId[2]).val(),
											success: function(ajaxResponse){
												$("#submitReplyStatus-"+splitId[1]+"-"+splitId[2]).removeClass("simpleAjaxLoader");
												switch(ajaxResponse){
													case "FAILED":
														alert('ERROR: Can\'t do it ... :(');
													break;
													case "SAMEREPORT": // do nothing (duplicates are taken care of)
													break;
													case "OK": // everything is OK
													default:
														$("#replyMessage-"+splitId[1]+"-"+splitId[2]).val("");
														//$("#reportReply-"+splitId[1]+"-"+splitId[2]).toggle('fast');
														$("#replyText-"+splitId[1]+"-"+splitId[2]).text("reply");
														$("#reportInfo-"+splitId[1]+"-"+splitId[2]).append(ajaxResponse);
														
														/*
														$("#reportAnswer-"+splitId[1]+"-new").click(function(){
															$("#reportAnswerOptions-"+splitId[1]+"-new").toggle('fast');
														}).mouseover(function(){
															$(this).addClass("reportMessageHover");
														}).mouseout(function(){
															$(this).removeClass("reportMessageHover");
														});*/
														
													break;
													
												}
											}
										});
										$("#submitReply-"+splitId[1]+"-"+splitId[2]).removeAttr("disabled");
									}
									return false;
								});
								
							break;
							
						}
					}
				});
				
			return false;
		});
	
	}
	
	updateReportLinks();
	
	// target all new report clicks
	$("[id*=startReport-]").click(function(){
		var splitId = this.id.split('-');
		$("#newReportDiv-"+splitId[1]).toggle('fast');
		return false;
	});
	
	// target all new report submission button clicks
	$("[id*=submitNewReport-]").click(function(){
		var splitId = this.id.split('-');
		
		if($("#newReportTitle-"+splitId[1]).val() == '' || $("#newReportTitle-"+splitId[1]).val() == 'undefined' || $("#newReportTitle-"+splitId[1]).val().length < 15){
			alert('Message title should be at least 15 characters long.');
			return false;
		}
		
		if($("#newReportMessage-"+splitId[1]).val() == '' || $("#newReportMessage-"+splitId[1]).val() == 'undefined' || $("#newReportMessage-"+splitId[1]).val().length < 30){
			alert('Your message, since it is a topic starter,\nshould be at least 30 characters long.');
			return false;
		}
		
		$("#submitReportStatus-"+splitId[1]).addClass("simpleAjaxLoader");
		
		$.ajax({
			type: "POST",
			url: "ajax_send_report.php",
			data: "q=" + splitId[1] + '&report_type=' + $("#newReportType-"+splitId[1]).val() + '&report_for=' + $("#newReportFor-"+splitId[1]).val() + '&title=' + $("#newReportTitle-"+splitId[1]).val() + '&message=' + $("#newReportMessage-"+splitId[1]).val(),
			success: function(ajaxResponse){
				$("#newReportTitle-"+splitId[1]).val("");
				$("#newReportMessage-"+splitId[1]).val("");
				switch(ajaxResponse){
					case "FAILED":
						alert('ERROR: Can\'t do it ... :(');
					break;
					default: // everything is most likely OK 
						$("#submitReportStatus-"+splitId[1]).removeClass("simpleAjaxLoader");
						$("#submitNewReport-"+splitId[1]).attr("disabled", "false");
						$("#newReportDiv-"+splitId[1]).hide('fast');
						$("#reportsModule-"+splitId[1]).hide('fast');
						$("#reportsModule-"+splitId[1]).html('');
						$("#reportsModule-"+splitId[1]).show('fast');
						$("#reportsModule-"+splitId[1]).addClass("simpleAjaxLoader");
						
						$.ajax({
							type: "POST",
							url: "ajax_get_reports.php",
							data: "q=" + splitId[1],
							success: function(ajaxResponse){
								switch(ajaxResponse){
									case "FAILED":
										alert('ERROR: All went well but I can\'r refresh the reports table...\nPlease reload the page ... :(');
									break;
									default: // everything is most likely OK 
										$("#submitReportStatus-"+splitId[1]).removeClass("simpleAjaxLoader");										
										$("#reportsModule-"+splitId[1]).removeClass("simpleAjaxLoader");
										$("#reportsModule-"+splitId[1]).html(ajaxResponse);
										updateReportLinks();
									break;
								}
								$("#submitNewReport-"+splitId[1]).removeAttr("disabled", "false");
									
									// target all remove thread links
									$("[id*=removeThread-]").click(function(){
										var splitId = this.id.split('-');
										
										if(confirm('Are you sure you want to remove the whole report?\n\n\This will remove all replies as well!')){	
											var tmpSpan = $("#removeThreadSpan-"+splitId[1]).html();
											$("#removeThreadSpan-"+splitId[1]).html("");
											$("#removeThreadSpan-"+splitId[1]).addClass("simpleAjaxLoader");
											
											$.ajax({
												type: "POST",
												url: "ajax_delete_report.php",
												data: "q=" + splitId[2],
												success: function(ajaxResponse){
													$("#filesDiv-"+splitId[1]).removeClass("simpleAjaxLoader");
													switch(ajaxResponse){
														case "FAILED":
															alert('ERROR: Can\'t do it ... :(');
														break;
														default: // everything is most likely OK
															$("#removeThreadSpan-"+splitId[1]).removeClass("simpleAjaxLoader");
															$("#reportInfoRow-"+splitId[1]+"-"+splitId[2]).remove();
															$("#report-"+splitId[1]+"-"+splitId[2]).remove();
														break;
														
													}
												}
											});
										
										}
										return false;
									});
							}
						});
						
					break;
					
				}
			}
		});
		return false;
		
	});
	
	// target all remove thread links
	$("[id*=removeThread-]").click(function(){
		var splitId = this.id.split('-');
		
		if(confirm('Are you sure you want to remove the whole report?\n\n\This will remove all replies as well!')){	
			var tmpSpan = $("#removeThreadSpan-"+splitId[1]).html();
			$("#removeThreadSpan-"+splitId[1]).html("");
			$("#removeThreadSpan-"+splitId[1]).addClass("simpleAjaxLoader");
			
			$.ajax({
				type: "POST",
				url: "ajax_delete_report.php",
				data: "q=" + splitId[2],
				success: function(ajaxResponse){
					$("#filesDiv-"+splitId[1]).removeClass("simpleAjaxLoader");
					switch(ajaxResponse){
						case "FAILED":
							alert('ERROR: Can\'t do it ... :(');
						break;
						default: // everything is most likely OK
							$("#removeThreadSpan-"+splitId[1]).removeClass("simpleAjaxLoader");
							$("#reportInfoRow-"+splitId[1]+"-"+splitId[2]).remove();
							$("#report-"+splitId[1]+"-"+splitId[2]).remove();
						break;
						
					}
				}
			});
		
		}
		return false;
	});
	
	// submit
	$("#newDeviceForm").submit(function(e){
		var validates = true;
		$("#errorsList").html("");
		$("#errors").hide("fast");
		
		if($("#udid").val() == '' || $("#udid").val().length != 40){ // device UDID
			$("#errorsList").append("<li>Please enter a valid UDID (40 characters exactly)</li>");
			validates = false;
		}
		
		if($("#device_name").val() == '' || $("#device_name").val().length < 4){ // device name
			$("#errorsList").append("<li>Please name your device (4 characters minimum)</li>");
			validates = false;
		}
		
		if(validates == false){ // show error and stop submit
			$("#errorTitle").show();
			$("#errors").show("fast");
			$('html, body').animate({scrollTop:0}, 'slow'); 
			return false;
		}
		
		// if all OK - then disable submit button while processing
		$("#submitButton").attr("disabled", "false");
		$("#submitStatus").addClass("ajaxLoader");
	});
	
});

// ]]>
