var audioPlayer = null;

jQuery.UpdateDialog = function(options) {
	var sectionId = options.sectionId;
	var clearFields = (options.clear !== undefined) ? options.clear : true;
	var openForm = (options.openForm !== undefined) ? options.openForm : true;
	var form = $("form[name='"+sectionId+"-form']");
	if(clearFields){
		$("input[type!=submit][type!=hidden],textarea",form).each(function(){$(this).val("")});
	}
	if(openForm) $('#'+sectionId+'-dialog').dialog('open'); 
	$('#ui-dialog-title-'+sectionId+'-dialog').attr("title",options.titleText).html(options.titleText);
	$('#'+sectionId+'-submit').val(options.buttonText);
	$(form).attr("action",options.formAction);
	if(options.userId !== undefined){
		$('#'+sectionId+'-user-id').val(options.userId);
	}
};

$(document).ready(function(){
		$('form').each(function(){$(this).validate();});
		
		$("form[name='reaction-form']").each(function(){
			$(this).validate({
				meta: "validate"
			});
		});
		
		$("form[name='update-profile']").validate({
			meta: "validate"
		});
		
		$("form[name='support-form']").validate({
			meta: "validate"
		});
		
		$('.last-input').keyup(function(event){
			if (event.keyCode == 13) {
				$(this).parents().closest('form').submit();
			}
		});
		
		$("select[name='downloads']").live("change",function(){
			if($(this).val() != "Download:"){
				//window.open($(this).val());
				window.location = $(this).val();
			}
		});

	
		/* - Toogle contorl for showing / hiding tracks realted to a package click event */
		$('.package-show-tracks').live("click",function(){
			$(this).parents().closest("fieldset").children().closest("div.package-track-listing").slideToggle("slow");
			if($(this).html() == "Listen/Download")
			{
				$(this).html("Hide tracks").attr("title","Hide tracks");
			}
			else if($(this).html() == "Show tracks")
			{
				$(this).html("Hide tracks").attr("title","Hide tracks");
			}
			else
			{
				$(this).html("Show tracks").attr("title","Show tracks");
				//$(this).html("Listen/Download").attr("title","Listen/Download");
			}
			
			return false;
		});
		
		$('a.package-statistics').live("click",function(){
			var slideButton = $(this);
			var packageId = $(this).parents().closest("fieldset").attr("id").split("-")[3];
			var sliderItem = $(this).parents().closest("fieldset").children().closest("div.package-statistics");
			if(sliderItem.is(':empty')){
				$('#content-loader').fadeIn('fast');
				$.ajax({
					  url: "/resource/include/backend/tabs/report-statistics.php?Pid="+packageId+"&Cid="+mainContactId,
					  cache: false,
					  success: function(html){
						$('#content-loader').fadeOut('fast');
						sliderItem.append(html);
						slideButton.html("Hide Statistics").attr("title","Hide Statistics");
						sliderItem.slideToggle("slow");
						
					  }
					});
			}else{
				sliderItem.slideToggle("slow");
				if($(this).html() == "Statistics")
				{
					$(this).html("Hide Statistics").attr("title","Hide Statistics");
				}
				else
				{
					$(this).html("Statistics").attr("title","Statistics");
				}				
			}

			return false;
		});
		
		$('a.self-submit').click(function(){
			$(this).closest("form").submit();
			return false;
		});
		
		/* -  Listen to audio - */
		$('#listen-to-audio-dialog').dialog({autoOpen: false, width:530,modal:false,close:function(){audioPlayer = null}});
		$('.package-track-listing a.track-listen').live("click",function(){
				var tr = $(this).parent().parent();
				var trId = tr.attr("id").split("-");
				trId = trId[trId.length - 1];
				loadPlaylist(trId);
				return false;
		});
		
		$("form[name='login'] a.submit").click(function(){
			$(this).parents().find("form").submit();
			return false;
		});
		
		$('#contact-add-edit-residencies-dialog').dialog({autoOpen: false, width:430,height:270});
		$("#contact-remove-residency-dialog").dialog({height: 160, width: 430,buttons:{'Yes': function() 
		{
			$("form[name='contact-remove-residency-form']").ajaxSubmit(
				{
					success:function(responseText)
					{
						$('#contact-residency-add-edit-row-'+responseText.success).remove();
						//$('#contact-residency-row-'+responseText.success).remove();
						$("#contact-remove-residency-dialog").dialog('close');
					},
					dataType:'json'
				}
			);
		}
		,Cancel: function() {$(this).dialog('close');}}
	});
		
				/* - Toogle view of residencies for contact click event - */
				$("a.show-hide-residencies").live("click",function(){
					var residencies = $(this).parent().parent().next().next().slideToggle("medium");					
					if($(this).html() == "View residencies") $(this).html("Hide residencies").attr("title","Hide residencies");
					else $(this).html("View residencies").attr("title","View residencies");
					return false;
				});
				
				$("a.show-hide-reactions").live("click",function(){
					var reactions = $(this).parent().parent().next().slideToggle("medium");					
					if($(this).html() == "View reactions") $(this).html("Hide reactions").attr("title","Hide reactions");
					else $(this).html("View reactions").attr("title","View reactions");
					return false;
				});
				
				/* - Add new residency click event - */
				$("a[title='Add new residency']").live("click",function(){
					$('#contact-add-edit-residencies-dialog').dialog('open');
					//$(":not([type=button])",).each(function(){$(this).val("")});
					$("form[name='contact-add-edit-residencies-form'] fieldset :input").each(function(){$(this).val("")});
					$("input[name='contact-add-edit-list-member-id']").val($(this).attr("href").substring(1));
					$.UpdateDialog({
						sectionId:'contact-add-edit-residencies',
						titleText:'Add recidency',
						buttonText:'Save',
						clear: false,
						formAction:'control.php?Section=Contact&Task=addUpdateResidencies'
					});
					return false;
				});
				
				/* - Submit new / edit click event- */
				$("form[name='contact-add-edit-residencies-form'] a.submit").click(function(){
					$(this).closest("form").submit();
					return false;
				});
				
				/* - View / Edit residency click event - */
				$("a[title='View/Edit residency']").live("click",function(){
					var residencyId = $(this).parent().parent().attr("id").split("-")[5];
					$("form input[name='contact-add-edit-residencies-id']").val(residencyId);
					$.UpdateDialog({
						sectionId:'contact-add-edit-residencies',
						titleText:'Edit residency',
						buttonText:'Save',
						formAction:'control.php?Section=Contact&Task=addUpdateResidencies'
					});
					$.getJSON("control.php?Section=Contact&Task=getResidencyInfo&ResidencyId="+residencyId,function(json){
						if(json.sessionTimeout !== undefined) window.location = "/account/login.php?message=sessionTimeout";
						for(var key in json){
							var updateItem = $('#contact-add-edit-residencies-'+key);
							updateItem.val(json[key]);
						}	
						$('#contact-add-edit-residencies-dialog').dialog('open');	
					});	
					return false;
				});
											
				/* - Delete residency click event - */
				$("a[title='Delete residency']").live("click",function(){
					var residencyId = $(this).parent().parent().attr("id").split("-")[5];
					$("input[name='contact-remove-residency-id']").val(residencyId);
					$('#contact-remove-residency-dialog').dialog('open');
					return false;
				});	
				
	
	$("#single-promote-package-confirm-dialog").dialog({height: 160, width: 430,buttons:{'Yes': function() 
		{
			$("form[name='single-promote-package-confirm-form']").ajaxSubmit(
				{
					success:function(responseText)
					{
						$("#single-promote-package-confirm-dialog").dialog('close');
					}
				}
			);
		}
		,Cancel: function() {$(this).dialog('close');}}
	});
	
	$(".promote-single-package").live("click",function(){
		var packageId = $(this).parents().closest(".report-listing").attr("id").split("-")[3];
		$('#single-promote-package-confirm-package-id').val(packageId);
		$('#single-promote-package-confirm-dialog').dialog('open');	
		return false;
	});
		
		
	/* Bens package audio download dialogue*/
	
	$('#download-audio-dialog').dialog({ autoOpen: false, width: 128,height:200}); 
	$('#download-audio-track-dialog').dialog({ autoOpen: false, width: 140,height:200}); 	
	
	$('#download-audio-dialog .links a').click(function(){
		$('#download-audio-dialog').dialog('close');
	});
	
	$(".track-package-download").live("click",function(){
		var packageId = $(this).parents().closest(".package-item, .report-listing").attr("id").split("-")[3];
		var types = ['wav','320','160','aac'];
		$('#download-audio-dialog .links a').each(function(i){
			$(this).attr("href","/otherutils/downzip.php?packageID="+packageId+"&fileType="+types[i]);
		});
		$('#download-audio-dialog').dialog('open');
		return false;
	});
		  
	/* Bens single track audio download dialogue*/
	$('#download-audio-track-dialog .links a').click(function(){
		$('#download-audio-track-dialog').dialog('close');
	});
	
	$(".track-package-download-link").live("click",function(){
		var packageId = $(this).parents().closest(".package-item, .report-listing").attr("id").split("-")[3];
		var trackIdArray = $(this).parent().parent().attr("id").split("-");
		var trackId = $(this).parent().parent().attr("id").split("-")[trackIdArray.length - 1];
		var types = ['wav','320','160','aac'];
		$('#download-audio-track-dialog .links a').each(function(i){
			$(this).attr("href","/otherutils/down.php?packageID="+packageId+"&fileType="+types[i]+"&fileID="+trackId);
		});
		$('#download-audio-track-dialog').dialog('open');
		return false;
	});
				
				setTimeout(function(){$('p.error-display').slideDown("fast")},300);
});

			function addEditResidency(json)
			{
				if(json.sessionTimeout !== undefined) window.location = "/account/login.php?message=sessionTimeout";
				var form = $("form[name='contact-add-edit-residencies-form']");

				var newRow = "";
				if(json.type != "edit") newRow+= "<tr id=\"contact-residency-add-edit-row-"+json.residencyInfo.id+"\">";

				newRow+= "<td width=\"200\">"+json.residencyInfo.name+"</td>";
				newRow+= "<td width=\"70\">"+json.residencyInfo.type+"</td>";
				newRow+= "<td width=\"80\">"+json.residencyInfo.freq+"</td>";
				newRow+= "<td width=\"200\">"+json.residencyInfo.add+"</td>";
				if(json.residencyInfo.filename == null){
					newRow+= "<td width=\"100\"><span><strong>No Flyer</strong></span></td>";
				}else{
					newRow+= "<td width=\"100\"><a href=\""+json.residencyInfo.filename+"\" class=\"button\" target=\"_blank\">View</a></td>";
				}
				newRow+= "<td width=\"165\">";
					newRow+= "<a href=\"#\" class=\"button left\" title=\"Delete residency\">Delete</a>";
					newRow+= "<a href=\"#\" class=\"button medium left\" title=\"View/Edit residency\">View / Edit</a>";
				newRow+= "</td>";
	
				if(json.type != "edit") newRow+= "</tr>";
				
				var table = $("#contact-residency-add-edit-table-"+json.contactId);
				if($("#contact-residency-add-edit-table-"+json.contactId+" tbody").children().size() == 0){
					table.parent().find("p").hide();
				}
				if(newRow != ""){
				if(table.css("display") == "none") table.css("display","block");
					if(json.type == "edit"){
						$("#contact-residency-add-edit-row-"+json.residencyInfo.id).html('').append(newRow);	
					}else{
						$("tbody",table).append(newRow);
					}
				}
				$('input[type!=submit]',form).each(function(){$(this).val("")});
				$('#contact-add-edit-residencies-dialog').dialog('close');
				$('input',form).attr("disabled",false);
			}
			
			function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
     }
     function loadPlaylist(playlistInfo) {
    	$.get('/resource/application/log/log.php?p=' + playlistInfo + '&action=listen');
		if(audioPlayer == null){
			$('#listen-to-audio-dialog').dialog('open');
			audioPlayer = new SWFObject('/resource/flash/audioPlayer.swf','ExternalInterfaceExample','508','300','9');
			audioPlayer.addParam('allowscriptaccess','always');
			audioPlayer.addParam('wmode','transparent');
			audioPlayer.addVariable('i',playlistInfo);
			audioPlayer.write('audio-container');
		}else{
			thisMovie("ExternalInterfaceExample").loadPlaylist(playlistInfo);
		}
		 
		 
     }
		
	function checkupload()
	{
		if($('#label-add-edit-label_logo').val() == '')
		{
			/*alert('Please select a file.'); 
			return false;*/
		}
		else
		{
			var ext = $('#label-add-edit-label_logo').val().split('.');
			ext = ext[ext.length-1];
			ext = ext.toLowerCase();
			if(ext in {'png':'', 'jpg':'','jpeg':''})
			{
				return true;
			}
			alert('Unsupported file type, please select png, jpg or jpeg.')
			return false;
		}
	}
