$(window).load(function(){
	var jcrop_api;
	var i, ac;
	var img =$("#recid").val()+".jpg" ;
	var full ="images/_full/";
	var tmp ="images/_tmp/";
	var uImg ;		

	if ( $("#imgLoad").length > 0 ) {
	new Ajax_upload('#imgLoad', {
		action: 'funcldr.php?func=rec_upload', 
		data : {
			'id' : $("#recid").val()
		},
		onSubmit : function(file , ext){
			if (ext && /^(jpg|png|jpeg|gif)$/.test(ext)){
                                $("#cropper").dialog('destroy');
				$('#img_load').removeClass("hidden");
				//alert($("#recid").val());
			} else {
				alert('Error: only images are allowed (.jpeg,.jpeg,.png,.gif).');// extension is not allowed
				return false;// cancel upload
			}
                        
		},
		onComplete : function(file,response){
			uImg =img+"?"+new Date().getTime();	
			$('#img_load').addClass("hidden");
                      
                        if (response=='[cropper]') {
				JcropClear();
				$("#cropbox").attr("src",tmp+uImg);			//Load the image into the cropper and the preview
				$("#preview").attr("src","images/noimage200.200.png");
				$('#cropbox').load(function(){
					try {
						jcrop_api.destroy();
					} catch(err) {
						//Handle errors here
					}		
					$('#cropperCont').dialog('open');
					if(navigator.userAgent.search(/msie/i)!= -1) { 
						$('#cropperCont').dialog('option', 'width',$('#cropbox').width()+235);
						$('#cropperCont').dialog('option', 'position', 'center');
					}
					initJcrop();
					$('#d_anchor').focus();	
              			});
                        } else if (response!='') {
				alert(response);
                        } else {
                            $("#main_img").attr("src",full+uImg);
                            $("#imgRemove a").attr({href: "#"});
                            $("#imgRemove").removeClass("ui-state-default").addClass("ui-state-active");
			}
		}

	});
	}

	//Delete the current image
	$('#imgRemove').click(function(){
		if ($("#imgRemove a").attr("href")){                    //If there is a link then    
			rmIMG();     
		}
		return false;						//Stop page jump for FF
	});

	function rmIMG() {
	$("#main_img").attr("src","images/noimage200.200.png");     //Put in the new images
	var pod = 'id=' + $("#recid").val();                           //Create values to post
	    $.post('funcldr.php?func=rec_img_del', pod,
	      function(txt) {
		if (txt!='') {
		    alert(txt);
		    //$("#imgRemove a").attr({href: "#"}); 
		} else {
		    //Toggle the save link
		    $("#imgRemove").removeClass("ui-state-hover").removeClass("ui-state-active").addClass("ui-state-default");
		    $("#imgRemove a").removeAttr("href")
		}
	    });
	}

	$('#imgHelp').click(function(){
		$('#helpCont').dialog('open');	
		$('#d_anchor2').focus();
                return false;			//Stop page jump for FF
	});


	function Jrefresh() {
		$('#cropbox').load(function(){
			jcrop_api.destroy();
			initJcrop();
              	});
	};

				
	function initJcrop() {
		jcrop_api = $.Jcrop('#cropbox');

		jcrop_api.setOptions({
			allowSelect: true,
			aspectRatio: 1,
			allowMove: true,
			allowResize:true,
			onChange: showPreview,
			onSelect: showPreview,
			sideHandles: false
		});

		clear();
		return true;
	};
				

	function checkCoords() {
		if (parseInt($('#w').val())) return true;
		alert('Please select a crop region then press save.');
		return false;
	};
			
			
	function showPreview(coords) {
		$('#x').val(coords.x);
		$('#y').val(coords.y);
		$('#w').val(coords.w);
		$('#h').val(coords.h);

		if (parseInt(coords.w) > 0) {
			var rx = 200 / coords.w;
			var ry = 200 / coords.h;

			var current_width = $('#cropbox').width();
			var current_height =$('#cropbox').height();

			jQuery('#preview').attr("src", function() { 
				return tmp+uImg; 
			})
			.css({
				width: Math.round(rx * current_width) + 'px',
				height: Math.round(ry * current_height) + 'px',

				marginLeft: '-' + Math.round(rx * coords.x) + 'px',
				marginTop: '-' + Math.round(ry * coords.y) + 'px'
			});
		} else {
			JcropClear();
		}
	}
			
		
	$("#helpCont").dialog({
		autoOpen: false,
		bgiframe: false,
		resizable: false,
		width:850,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			"OK": function() {
				$(this).dialog('close'); 
			}
		}
	});



	$("#cropperCont").dialog({
		autoOpen: false,
		bgiframe: false,
		resizable: false,
		width:'auto',
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			Cancel: function() {
				$(this).dialog('close');
			},
			'Clear': function() {
				clear();JcropClear();		
			},
			'Save': function() {
				if (checkCoords()) {			
					var pod = 'id=' + $("#recid").val() + '&x='+$('#x').val()+ '&y='+$('#y').val()+ '&w='+$('#w').val()+ '&h='+$('#h').val();
					$.post(
						'funcldr.php?func=rec_perf_crop',
						pod,
						function(txt) {
							if (txt!='') {
								alert(txt);
							} else {
								$("#main_img").attr("src",full+uImg);
								$("#imgRemove a").attr({href: "#"});
                            					$("#imgRemove").removeClass("ui-state-default").addClass("ui-state-active");
                            				}
						}
					);			
					$(this).dialog('close');
				}
			}
		}
	});

	function JcropClear() {
		$('#x').val("");
		$('#y').val("");
		$('#w').val("");
		$('#h').val("");

		jQuery('#preview')
			.attr("src", function() { 
				return "images/noimage200.200.png"; 
			})
			.css({
				width:  '200px',
				height: '200px',
				marginLeft: '0px',
				marginTop: '0px'
			});
	}
						
		
	function clear() {
		jcrop_api.release();
	};

	//===================
	//Comments tab
	//=====================
	$("#comment").charCounter(140, {
		container: "#counting_left",
		pulse: false,
		format: "%1"
	});
	
	//On page load 
	fetch_com(1,1);		//get comments and paging
	$("#write_com").hide();	//Hide the add comment section
	
	function get_comment(page,maxpage) {
	  var pod = 'id='+$("#recid").val()+'&m='+maxpage+'&p='+page+'&oi='+$("#origid").val();
	  $.post(
		'funcldr.php?func=rec_get_comments',
		pod,
		function(txt) {
			$("#comments").html( txt);
			$('.hover-star2').rating();
		}
	  );
	}
	
	$(".paging").live("click", function(){		  
		fetch_com($(this).attr("page"),$(this).attr("mp"));
		return false;
	});
	
	function fetch_com (page,maxpage) {
		get_comment(page,maxpage);
		get_com_paging(page);
	}
	
	//rec_nav
	function get_com_paging (page) {
		var pod = 'id='+$("#recid").val()+'&fpg='+page+'&oi='+$("#origid").val();

		$.post(
		      'funcldr.php?func=rec_get_comments_pgcnt',
		      pod,
		      function(txt) {
			      $("#rec_nav").html( txt);
		      }
		);
	}
	
	$('#showcom').click(function(){
		if ($('#showcom').html()=='Cancel Review') {
			$('#showcom').html('Add Review');
			$("#write_com").hide('blind');
		} else if ($('#showcom').html()=='Add Review') {
			$("#write_com").show('blind');
			$('#showcom').html('Cancel Review');
		} else if ($('#showcom').html()=='Cancel Edit') {
			$("#write_com").hide('blind');
			$('#showcom').html('Edit Review');
		} else if ($('#showcom').html()=='Edit Review') {
			$("#write_com").show('blind');
			$('#showcom').html('Cancel Edit');
	   }
	   
		$('#blank_link').focus();
		return false;						//Stop page jump for FF
	});
	
	
	$('#frmcomment').submit(function() {
		//getting values and send ajax
		var e=$('input[name=rdeasiness]:checked').val();
		var t=$('input[name=rdtastyness]:checked').val();
		var c=$('#comment').val();
		var pod = 'id='+$("#recid").val()+'&e='+e+'&t='+t+'&c='+c+'&oi='+$("#origid").val();
		$.post(
		      'funcldr.php?func=rec_put_comments',
		      pod,
		      function(txt) {
			      if (txt!='') {alert(txt);}
			      fetch_com(1,1);
		      }
		);
		
		//Hide comment section
		$("#write_com").hide('blind');
		$('#showcom').html('Edit Review');
		$('#comm_del').removeClass('hidden');
		$('#comm_add').attr("src","images/button/update.png");

		
		return false;
	});
	
	$('#comHelp').click(function(){
		$('#helpComm').dialog('open');	
		$('.takefocus').focus();
		return false;			//Stop page jump for FF
	});
	
/*try to use the other dialog help box here, attach it to a help class*/
	$("#helpComm").dialog({
		autoOpen: false,
		bgiframe: false,
		resizable: false,
		width: 850,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			"OK": function() {
				$(this).dialog('close'); 
			}
		}
	});
	
	$('.hover-star2').rating({
	  focus: function(value, link){
	    var tip = $(this).attr('cont');
	    $("#"+tip)[0].data = $("#"+tip)[0].data || $("#"+tip).html();
	    $("#"+tip).html(link.title);
	  },
	  blur: function(value, link){
	    var tip = $(this).attr('cont');
	   $("#"+tip).html('');
	  }
	});
	
	$('#comm_del').click(function(){
		var pod = 'id='+$("#recid").val();
		$.post(
		      'funcldr.php?func=rec_del_comm',
		      pod,
		      function(txt) {
			      if (txt!='') {alert(txt);}
			      fetch_com(1,1);//show first page
		      }
		);
		
		//Hide comment section
		$("#write_com").hide('blind');
		$('#showcom').html('Add Review');
		$('#comm_del').addClass('hidden');
		$('#comm_add').attr("src","images/button/add.png");
		$('#comment').val('');
		//$(".hover-star2").attr('checked', false);
		$('.hover-star2').rating('select','') 
		return false;						//Stop page jump for FF
	});
	//===================
	//Comments tab
	//=====================
});