$(document).ready(function(){
	$('#error').corner('5px');
	$('#updated').corner('5px');
	$('.format_head').corner('3px');
	$('li.rounded').corner('3px');
	
	$(".format_body").hide();
	
	
	$(".fadein_message").slideDown("fast");
	
	
	// toggle formats
	/*
	$(".format_head").click(function(){
		$(".format_body").slideUp('fast');
		$(this).next(".format_body").slideToggle('slow');
	});
	*/

	
	$(".format_head .header").toggle(function(){
		$(this).parent().next().slideDown('fast');

		$(this).prev().removeClass('format_hide');
		$(this).prev().addClass('format_show');
	}, function(){
		$(this).parent().next().slideUp('fast');
		$(this).prev().removeClass('format_show');
		$(this).prev().addClass('format_hide');
	});	
	
	
	//briefing upload button
	var cbriefing_control = $('#cbriefing_control').val();
	if(cbriefing_control != null){
		new AjaxUpload('#cbriefing_control', {
			//action: 'upload.php',
			action: '/concept/uploadbriefing',
			name: 'cbriefing_control',
			onComplete : function(file, response){
			    $('#cbriefing').val(response);
				$('#uploaded_briefing').html('Uploaded File: ' + file);
			}	
		});	
	}
	
	//upload addocs
	var cbriefing_control = $('#caddocsfile_control').val();
	if(cbriefing_control != null){
		new AjaxUpload('#caddocsfile_control', {
			//action: 'upload.php',
			action: '/concept/uploadaddocs',
			name: 'caddocsfile_control',
			onComplete : function(file, response){
			    $('#caddocsfile').val(response);
				$('#uploaded_caddocsfile').html('Uploaded File: ' + file);
			}	
		});	
	}
	
	// Make AJAX Uploader for each input on the formats page of developers
	// For flash uploadform only
	i=0;
	// Loop for selecting all the file-upload-forms on the page. Each inut has an id starting with dev_upload_input_flash_ followed by the format_id
	$.each($("input[name^='dev_upload_input_flash']"), function() { 
		// get the id for selecting the file-inputfield
		fileinput_id=$(this).attr('id');
		js_id='#' + fileinput_id;
		
		// If file-input field is not empty, file is selected and upload needs to start.
		var cbriefing_control = $(js_id).val();
		if(cbriefing_control != null){
			  // Get the id form the hidden input
			  format_id_selector=$(this).next().attr('id');
			  format_id_selector_js = '#' + format_id_selector;
			  id=$(format_id_selector_js).val();
			  
			  // remeber id for OnComplete. Otherwise, by the time the uplaod has been completed , the second loop will overwrite previous id
			  var id_data_flash= new Array
			  id_data_flash[i]=id;
			  
			  //Call the Ajax upload;
				new AjaxUpload($(js_id), {
					action: '/format/upload_flash',
					name: fileinput_id,
					data: {
					    format_id : id
					  },
					onChange : function(file,extension){
						if(extension!='swf')
						{
							alert('Only *.swf files are allowed. Please choose a correct file.');
							return false;
						}

						$('.upload_message').slideDown('fast');
						$('.upload_message').html("Uploading file");
					  },
					onComplete : function(file, response){			
						$('.upload_message').html(response);
					}	
				});	
			}
		  i++;
		});
	
	// Make AJAX Uploader for each input on the formats page of developers
	// For *.gif uploadform only
	i=0;
	// Loop for selecting all the file-upload-forms on the page. Each inut has an id starting with dev_upload_input_flash_ followed by the format_id
	$.each($("input[name^='dev_upload_input_gif']"), function() { 
		// get the id for selecting the file-inputfield
		fileinput_id=$(this).attr('id');
		js_id='#' + fileinput_id;
		
		// If file-input field is not empty, file is selected and upload needs to start.
		var cbriefing_control = $(js_id).val();
		if(cbriefing_control != null){
			  // Get the id form the hidden input
			  format_id_selector=$(this).next().attr('id');
			  format_id_selector_js = '#' + format_id_selector;
			  id=$(format_id_selector_js).val();
			  
			  // remeber id for OnComplete. Otherwise, by the time the uplaod has been completed , the second loop will overwrite previous id
			  var id_data_gif= new Array
			  id_data_gif[i]=id;
			  
			  //Call the Ajax upload;
				new AjaxUpload($(js_id), {
					action: '/format/upload_gif',
					name: fileinput_id,
					data: {
					    format_id : id
					  },
					onChange : function(file,extension){
						if(extension!='gif')
						{
							alert('Only *.gif files are allowed. Please choose a correct file.');
							return false;
						}		  	
						$('.upload_message').slideDown('fast');
						$('.upload_message').html("Uploading file");
						
					  },
					onComplete : function(file, response){			
						$('.upload_message').html(response);
					}	
				});	
			}
		  i++;
		});

		
	//create concept with formats
	$('#create_concept_button').click(function(){
		$(this).val('Processing...').attr('disabled','disabled');
		
		var campaign_id = $('#campaign_id').val();
		$.post('/concept/create/' + campaign_id,$("#create_concept").serialize(), function(data) {
			//redirect to campaign
			window.location.href = '/manager/campaign/' + campaign_id;
		});
	});
	
	//update concept with formats
	$('#edit_concept_button').click(function(){
		$(this).val('Processing...').attr('disabled','disabled');
		
		var concept_id = $('#concept_id').val();
		$.post('/concept/edit/' + concept_id,$("#edit_concept").serialize(), function(data) {
			//redirect to campaign
			window.location.href = '/concept/edit/' + concept_id + "/1";
		});
	});
	
	
	// Reload the format form when template is selected
	$('#format_template_selector').change(function(){
		url = "/format/load_format_template/" + $(this).val();
		$('#ajax_format_form').load(url);
	});
	
	// Submit the create-format-form
	$("#submit_new_format").click(function(){
		$('#submit_new_format').attr("disabled", "true");
		$('#new_format_form').submit();
	});
	
	
	/* 
	 * Delete a format using ajax. If it succeeds, hide the format. The format will be hidden on the active page. Since
	 * it is deleted in the db, it will not show on the next page-reload 
	 */
	$('.delete_format').click(function(){
		bordercolor = $(this).parent().parent().css("border-color");
		$(this).parent().parent().css("border-color","red");
		if(confirm("Are you sure you want to delete this format?"))
		{
			url = "/format/delete_ajax/"+ $(this).attr('title');
			$.ajax({ url: url, success: function(data){
				$('#format_'+data).parent().parent().hide();
				$('#format_'+data).parent().parent().next().hide();
		      }});
		}else{
			$(this).parent().parent().css("border-color",bordercolor);
			return false;
		}
	});
	
	/* 
	 * Delete a campaign using ajax. If it succeeds, hide the campaign. The campaign will be hidden on the active page. Since
	 * it is deleted in the db. It will not show on the next page-reload 
	 */
	$('.delete_campaign').click(function(){
		bordercolor = $(this).parent().parent().css("border-color");
		$(this).parent().parent().css("border-color","red");
		if(confirm("Are you sure you want to delete this campaign? All the containing concepts & formats will be lost."))
		{
			url = "/campaign/delete/"+ $(this).attr('alt');
			$.ajax({ url: url, success: function(data){
				$('#campaign_'+data).parent().parent().hide();
		      }});
		}else{
			$(this).parent().parent().css("border-color",bordercolor);
			return false;
		}
	});
	
	/* 
	 * Delete a concept using ajax. If it succeeds, hide the concept. The concept will be hidden on the active page. Since
	 * it is deleted in the db. It will not show on the next page-reload 
	 */
	$('.delete_concept').click(function(){
		bordercolor = $(this).parent().parent().css("border-color");
		$(this).parent().parent().css("border-color","red");
		if(confirm("Are you sure you want to delete this concept? All the containing formats will be lost."))
		{
			url = "/concept/delete/"+ $(this).attr('alt');
			$.ajax({ url: url, success: function(data){
				$('#concept_'+data).parent().parent().hide();
		      }});
		}else{
			$(this).parent().parent().css("border-color",bordercolor);
			return false;
		}
	});
	
	
	/* Hide the laguage dropdown menu if user chooses to use them all */
	$('#copylaguages').change(function () {
	    if ($(this).attr("checked")) {
	        $('#language').hide();
	    } else {
	    	$('#language').show();
	    }
	});
	
	
	/* Mark the project as done if user checks the checkbox */
	$('.markasdone').change(function(){
		element = $(this);
		if($(this).val()=="on")
		{
			marker = "on";
		}else{
			marker = "off";
		}
		url = "/format/mark_as_done/" + $(this).attr("id") + '/' + marker;
		$.ajax({ 
			url: url,
			beforeSend: function(){
				$(element).prev().show();
			}, success: function(data){
				$(element).prev().hide();
			},error:function(){
				alert("Our apologies. The action could not be saved. Please try again later.")
		}});
	});


	
});

// date picker
$(function(){
	$('.date-pick').datePicker();
});	

/* 
 * Feedback functions  
 */
function parseFeedbackData(data)
{
	if (data.no_feedback != 1) {
	    $.each(data, function(i, value) {              
	    	var last_div = $('#feedback div:last').attr('id');
	        var new_div  = eval(last_div)+1;                    
	        
	        if (value.format == 0) {
	        	$("#1").clone().removeAttr('id').removeClass('hidden').attr('id', new_div).addClass(value.account.role).appendTo("#feedback")
	            .find('.subject').html(value.subject).end()
	            .find('.message').html(value.message).end()
	            .find('.dateinfo').html(value.posted).end();
	        } else {
	        	$("#1").clone().removeAttr('id').removeClass('hidden').attr('id', new_div).addClass(value.account.role).appendTo("#feedback")
	            .find('.format_val').html(value.format_name).end()
	            .find('.subject').html(value.subject).end()
	            .find('.message').html(value.message).end()
	            .find('.dateinfo').html(value.posted).end();
	        }
	    });
	}

    $('#loader').hide();
    $('#feedback').show();
}



