// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/* I tried this and it doesn't work because it doesn't resize the image. */
/*
jQuery(document).ready(function() {
  $("img").crop(3,3,3,3);
});
*/
//jQuery.noConflict();
var Plumelo = {
}
Plumelo.email = function(form)
{
    $('spinner').show();
	if(Plumelo.validateEmailForm(form))
		new Ajax.Request(form.action,{
 		methods: 'post',
 		parameters:form.serialize(true),
 		asynchronus: true,
 		onComplete: function(response){
			$('controls').innerHTML = "<div id='flash'style='margin-top:10px;margin-left:105px;'><p>" + response.responseText + "</p></div>";
			$('controls').innerHTML += "<p class='closewindow' ><a href='#' class='button_fluid' onclick='Modalbox.hide();return false;'><span>Close Window</span></a></p>"
			Modalbox.resizeToContent();
			$('spinner').hide();
 		}
 	})
	else return false;
}
Plumelo.ajaxPaginate = function(container, action,paginator_id,spinner , options , params,method){
	if(!params)
    	params = "" 
	if(!method)
	    method = "get"	
   new Ajax.Updater(container , action, {'asynchronus':true , evalScripts:true ,'method':method, 
   										  'parameters':params,
                                           onLoading: function(){
										   	if(options['onLoading'])
											 eval(options['onLoading']);
										   	if(!$(spinner).visible())
										      $(spinner).show();
										   },
                                           onComplete: function(){
					    					  if (options) {
											  	eval(options['onComplete']);
											  }
											  if(spinner)
											   Effect.Fade(spinner);
                                              Plumelo.ajaxifyPaginate(container,paginator_id,spinner);
                                           }
                                        }
                    )	
}
Plumelo.ajaxifyPaginate=function(container,paginator_id,spinner){
 $$("#" + paginator_id + " a").each(function(a){
     a.onclick = function(){
	 	new Ajax.Updater(container, this.href , {'asynchronus':true , 'method':'get' , evalScripts:true , onLoading: function(){$(spinner).show();}, onComplete: function(){Plumelo.ajaxifyPaginate(container , paginator_id , spinner);$(spinner).hide();}} );
		return false;
		} 	
   })
}


Plumelo.ajaxifyPaginatedSection=function(container,spinner){
	
$$(".pagination a").each(function(a){	
     a.onclick = function(){
	 	new Ajax.Updater(container, this.href , {'asynchronus':true , 'method':'get' , evalScripts:true , onLoading: function(){$(spinner).show();}, onComplete: function(){Plumelo.ajaxifyPaginatedSection(container, spinner);$(spinner).hide();}} );
		return false;
		} 	
   })
}

Plumelo.dragBookmarks = function(){
  $$(".bookmark").each(function(bookmark){
  	new Draggable(bookmark.id, {
  		constraint: 'vertical'
  	});
  })	
}
Plumelo.deleteRecipeFromPlan= function(user_id){
  if($('selected_bookmark_value')){    
  	bookmark_id = $('selected_bookmark_value').value
  	date = $('selected_day_value').value 
  	new Ajax.Request("/users/" + user_id + "/plan/" + date + "/" + bookmark_id + "/delete",{
   		methods: 'get',
   		parameters:{'plan[bookmark_id]': bookmark_id , 'plan[target_date]':date , 'authenticity_token':$('token').value},
   		asynchronus: true,
   		onComplete: function(response){
   			Plumelo.ajaxPaginate('day_plans', "/users/" + user_id + "/plans/" + date + "/day_plans" ,'paginate_day');
  			if (response.responseText != "Deletion failed!")
  				$(date).innerHTML = response.responseText;
  			else 
  				alert(response.responseText);
   		}
   	})	
  }
}
Plumelo.deleteDayPlan=function(user_id){
	date = $('selected_day_value').value 
	new Ajax.Request("/users/" + user_id + "/plan/" + date + "/delete",{
 		methods: 'get',
 		parameters:{'authenticity_token':$('token').value},
 		asynchronus: true,
 		onComplete: function(response){
 			Plumelo.ajaxPaginate('day_plans', "/users/" + user_id + "/plans/" + date + "/day_plans" ,'paginate_day');
			if (response.responseText != "Deletion failed!")
				$(date).innerHTML = '0';
			else 
				alert(response.responseText);
 		}
 	})	
}
Plumelo.deleteWeekPlan=function(user_id){
	date = $('selected_day_value').value 
	new Ajax.Request("/users/" + user_id + "/plan/" + date + "/delete_week",{
 		methods: 'get',
 		parameters:{'authenticity_token':$('token').value},
 		asynchronus: true,
 		onComplete: function(response){
 			Plumelo.ajaxPaginate('day_plans', "/users/" + user_id + "/plans/" + date + "/day_plans" ,'paginate_day');
      if (response.responseText != "failed")
        $$('.recipe_count').each(function(e){e.innerHTML = '0'})
      else
        alert("Deletion failed!");      
 		}
 	})	
}
Plumelo.addToPlan= function(user_id , bookmark_id , modal){
	date = $('selected_day_value').value;
	$('plans_spinner').show();
	new Ajax.Request("/users/" + user_id + "/plans/",{
 		methods: 'post',
 		parameters:{'plan[bookmark_id]': bookmark_id , 'plan[target_date]':date , 'authenticity_token':$('token').value, 'from_modal':modal},
 		asynchronus: true,
 		onComplete: function(response,transport){
			 if(!transport)
 			 Plumelo.ajaxPaginate('day_plans', "/users/" + user_id + "/plans/" + date + "/day_plans" ,'paginate_day', null , {'onComplete': "new Effect.Highlight('day_plans');$('plans_spinner').hide();"});
			 $(date).innerHTML = response.responseText;
			 $('shopping_list_spinner').innerHTML = (transport[0]['errors']);
 			 $('plans_spinner').hide();
     		 new Effect.Highlight('shopping_list_spinner', {
        	 endcolor: '#ff5555' });
			 $('shopping_list_spinner').show();
			 $('shopping_list_spinner').fade({duration: 3})
			//$('bookmark_' + bookmark_id).id = "dragged_bookmark_" + bookmark_id;
			//$('dragged_bookmark_' + bookmark_id).hide();
 		}
 	})
 	if (modal=='yes')
 	{
 	Modalbox.hide();return false;
 	}
}

Plumelo.confirmPlan= function(user_id , bookmark_id){
	date = $('selected_day_value').value;
	$('plans_spinner').show();
	new Ajax.Request("/users/" + user_id + "/plans/" + bookmark_id + "/check_plan_confirmation",{
 		method: 'get',
 		parameters:{'bookmark_id': bookmark_id , 'target_date':date , 'authenticity_token':$('token').value},
 		asynchronus: true,
 		onComplete: function(response,transport){
 		$('plans_spinner').hide();
 		}
 	})
}

Plumelo.is_private = function(user_id,bookmark_id){
	new Ajax.Request("/users/" + user_id + "/bookmarks/" + bookmark_id + "/is_private_false",{
 		method: 'get',
 		parameters:{'id': bookmark_id},
 		asynchronus: true,
 		onComplete: function(response,transport){
 		Modalbox.hide();
 		document.getElementById("is_private_0").checked = true;
 		}
 	})
}


Plumelo.validateEmailForm = function(form)
 { 
 $('error_div').innerHTML = "";
 var errorMessage = "<ul>"; 
 var emailRegexp = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
 var emails = form['to'].value.split(",");
 var error = false;
 emails.each(function(email){
 	if(!email.strip().match(emailRegexp)){ error = true; } 
 })
 if(error) {
 	errorMessage += "<li>One or more of the emails you have entered is not valid</li>";
 }
 
 errorMessage+="</ul>";
 if (errorMessage != "<ul></ul>") {
 	$('error_div').innerHTML = errorMessage;
	$('error_div').show();
	Modalbox.resizeToContent();
	$('spinner').hide();
 return false;}
 else{return true;}
}

Plumelo.validatContactlForm = function(form ,error_div)
 { 
 $(error_div).innerHTML = "";
 var errorMessage = "<ul>"; 
 var emailRegexp = /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
 var email = form['email'].value
 var error = false;
 	if(!email.strip().match(emailRegexp)){ 
	errorMessage += "<li>The email you have entered is not valid</li>";
	error = true;} 
 if(form['body'].value.strip()== "" ){ 
 error =true; 
 errorMessage += "<li>You can't leave the body blank</li>";}
 
 errorMessage+="</ul>";
 if (errorMessage != "<ul></ul>") {
 	$(error_div).innerHTML = errorMessage;
 	$(error_div).show();
 }
 if(error) 
  return false;
 else 
  return true;
}


Plumelo.bookmark = function(form)
{		
        $('recipes_spinner').show();
		document.getElementById('save_plummelo').disabled=true; 
		new Ajax.Request("/bookmarks/create", {
 		methods: 'post',
 		parameters:form.serialize(true),
 		asynchronus: true,
 		onComplete: function(response, transport){
 			Plumelo.CloseOrShowErrors(response,transport)
 		 $('recipes_spinner').hide();
 		}
 	})
}
Plumelo.SaveRecipeOrShowErrors = function(response){
	if (response.responseText == 'You Have Saved this recipe Before.') {
		$('errors_div').innerHTML = response.responseText;
		$('errors_div').show();
	}
	else 
		if (response.responseText == 'Recipe Saved') {
			alert(response.responseText)
			window.close();
		}
}

Plumelo.CloseOrShowErrors = function(response,transport){
	if(transport[0]['result'] == true)
       self.close();
	else{
		if(!window.location.href.match(/#$/))
		 window.location+="#";
		else
    		window.location=window.location;
    		$('recipes_spinner').hide();
    		document.getElementById('save_plummelo').disabled=false; 
    		$('errors_div').show();	
    		$('my_ingredients').show();	
    		$('my_notes').hide();	
    		errors = transport[0]['errors'];
		if(errors.length > 1 )
		$('errors_div').innerHTML = "<h2>" + errors.length  +" errors prohibited this recipe from being saved</h2><p>There were problems with the following fields:</p>";
		else
		$('errors_div').innerHTML = "<h2>1 error prohibited this recipe from being saved</h2><p>There were problems with the following fields:</p>";
		errors.each(function(error){
		 $('errors_div').innerHTML += "<p><ul><li>" + error+ "</li></ul></p>";
		}
		)
		/*if(transport[1]['invalid_recipe_name'])
		{
		  alert(transport[1]['invalid_recipe_name']);
		  $('span.recipe_name_span').addClass('fieldWithErrors');
		}*/
		$$('.ingredient').each(function(i){
		  if(i.style.display  != "none") 	
           i.remove();
        })
		Insertion.Bottom("ingredients",response.responseText);
	}
}

Plumelo.scrape = function(form)
{ 
 	//$('scrape_button').hide();
	$('errors_div').hide();
 	Effect.Appear($('recipes_spinner'));
 	new Ajax.Request("/bookmarks/scrape", {
 		methods: 'post',
 		parameters: {
 			'bookmark[uri]': $('bookmark_uri').value
 		},
 		asynchronus: true,
 		onComplete: function(response, transport){
 			Plumelo.FillReceivedData(response ,transport);
 		}
 	})
}
Plumelo.FillReceivedData = function(response,transport)
{ 
 $('recipes_spinner').hide();
 
 if (response.status != 200)
 {
   Modalbox.show($('ConfirmationPopup'), {title: this.title  , width:570}); return;
 }
 
 if (response.status == 200) {
  if (transport[2]['ingredients_size'] > 1)
  {
  $$('.ingredient').each(function(i){
  	if(i.style.display  != "none") 	
     i.remove();
   })
  } 	
  
  if(transport[2]['recipe_name'] == "" && transport[2]['ingredients_size'] <= 1)
  {
   Modalbox.show($('SccrappingFailed'), {title: this.title  , width:570}); return;	
  }
  
  if(transport[2]['timeout_error'] || transport[2]['ingredients_size'] <= 1)
  {
   Modalbox.show($('ConfirmationPopup'), {title: this.title  , width:570}); return;	
  }
  
  if(transport[0]['errors'])
  {
   $('errors_div').show();	
   $('errors_div').innerHTML = "<h2>1 error prohibited the scraping operation to be completed</h2><p><ul><li>" +transport[0]['errors']+"</li></ul></p>";
   return;	
  }
  	Insertion.Bottom("ingredients",response.responseText);
	$('ingredients_size').innerHTML = $$('.ingredient').size();
  	if ((transport[0] != "") && (transport[0] != null)) {
		$('bookmark_serving_size').value = transport[1];
		new Effect.Highlight('bookmark_serving_size', {
  			duration: 3
  		});
  		     $('scrape_button').hide();
			}
			else {  $('scrape_button').value = "Reload" ;
			        Effect.Appear('scrape_button');
			}
			if ((transport[1] != "") && (transport[1] != null)) {
				$('bookmark_short_description').value = transport[0];
				new Effect.Highlight('bookmark_short_description', {
					duration: 3
				});
			  $('scrape_button').hide();
			}
			else { $('scrape_button').value = "Reload Recipe";
			 Effect.Appear('scrape_button'); 
			}
		}
		else{ 
			 /*
			 $('errors_div').show();	
             $('errors_div').innerHTML = "<h2>Loading Recipe Failed, Press the Load button to try again</h2>"; 
			 $('scrape_button').value = "Load";
			 Effect.Appear('scrape_button'); 
			 */
			 Modalbox.show($('ConfirmationPopup'), {title: this.title  , width:570}); return;
		}
		
}

Plumelo.ShowConfirmationBox=function(id){
    Modalbox.show(id, {title: this.title  , width:570});
}

Plumelo.RemoveHeadersIfNoIngredientsExists =function(){
	
	ingredientsCount = $$('.ingredient').size();
	if(ingredientsCount <= 1)
	 $('header').hide();
}

Plumelo.AddHeaderWhenAddingTheFirstIngredient = function(){
	ingredientsCount = $$('.ingredient').size();
	 if(ingredientsCount <= 1)
	  $('header').show();
}

jQuery(document).ready(function() {
 // jQuery('.bookmark-content').cornerz();
  // ajaxTagCloud();
});

function reset() {
  jQuery("li.fade").removeClass('fade');
  jQuery("a.selected").removeClass('selected');

}


Plumelo.addIngredient = function(html)
{
	Plumelo.AddHeaderWhenAddingTheFirstIngredient();
	Insertion.Bottom("ingredients",html);
	
	var ingredientsCount = parseInt($('ingredients_size').innerHTML) + 1;
	
	var ingredientsRowsCount =  $$("#ingredients tr").size();
	$('ingredients_size').innerHTML = ingredientsCount;
	
	var lastIngredient = $$("#ingredients tr")[ingredientsRowsCount -1];
	lastIngredient.setAttribute("class" , "ingredient");

	lastIngredient.down('.amount').setAttribute('name' , "bookmark[new_ingredient_attributes]["  + ingredientsCount +  "][amount_string]");
	lastIngredient.down('.amount').setAttribute('value' , "");
	
	lastIngredient.down('.ingredient_name').setAttribute('name' , "bookmark[new_ingredient_attributes]["  + ingredientsCount +  "][name]");
	lastIngredient.down('.ingredient_name').setAttribute('value' , "");
	
	lastIngredient.down('.measure select').setAttribute('name' , "bookmark[new_ingredient_attributes]["  + ingredientsCount +  "][measure_id]");
	lastIngredient.down('.measure select').selectedIndex =0;
	
	//lastIngredient.down('.category select').setAttribute('name' , "bookmark[new_ingredient_attributes]["  + ingredientsCount +  "][category_id]");
	//lastIngredient.down('.category select').selectedIndex =0;
	
	return false;
}


Plumelo.alertIfKnowIngredientsAreEntered = function(value)
{
	if(value == 3) return true; //If Saved from another user..
	var valid = false;
	if($$('.ingredient').size() < 2)
	 {
	 	var submit=confirm("You are about to save a recipe to Plummelo without ingredient information. If you do, other features like My List will not work properly. Do you still want to save?");
		if (!submit) {
			return false;
		}
	 }
 	 return true;
	
}
// start drop down in plan for week plan and day plan
var mtimeout	= 300;
var closetimer	= 0;
var ddmenuitem	= 0;

function mopen(id)
{	
    mcancelclosetime();
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}
function mclosetime()
{
	closetimer = window.setTimeout(mclose, mtimeout);
}

function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}
document.onclick = mclose; 
// end my plan

Plumelo.printShoppingList = function(){
	/*result = confirm('After printing, do you want to clear all items and recipes in the shopping list?');	*/
	/*hidebox('print_popup');*/
	Modalbox.hide()
    input = '#combined_items';
	var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
    disp_setting+="scrollbars=yes,width=650, height=600, left=100, top=25";
	var docprint=window.open("","",disp_setting); 
	var html = "<head><link type='text/css' rel='stylesheet' media='all' href=/stylesheets/screen.css?1234452054'>"
	html += "<style>body{background:none!important}.small_button{display:none}#content_container21{display:none}#combined_list_ingredients_i_have{margin-left:30px;text-align:left;}#combined_list_recipes{margin-left:30px;text-align:left;}.left_lists{margin-left:30px;text-align:left;}</style></head>"
	html+= "<body><div class='ingradients_list' style='margin-left:30px;'><input value='Plummelo' type='image' src='/images/plummelo_email.jpg' width=640 alt='plummelo'/></div><div class='lists'>";
	html+= $$(input)[0].innerHTML;
	html+= "</div></body>"
	docprint.document.write(html);
	docprint.document.close();
	docprint.focus();
    /*if(result)
 	 return true;
	else
	 return false;*/
}

Plumelo.printPopUp = function(id)
 {  
    url = "/users/"+ id +"/clear_shopping_list"
    popUpContent = "<center><br/>"
    popUpContent += "After printing, do you want to clear all items and recipes in the shopping list? <br/><br/><br/>"
    popUpContent += "<a href=# class='button' onclick = hidebox('print_popup')> Cancel </a>"
    popUpContent += "<a href="+url+" class='button_lrg' onclick = 'return Plumelo.printShoppingList();'>Print and clear list</a>"
    popUpContent += "<a href='#' class='button_lrg' onclick = 'return Plumelo.printShoppingList();'>Print and keep list</a>"
    popUpContent += "</center>"
    new popUp(330, 200, 400, 150, "print_popup", popUpContent , "white", "black", "bold 10pt sans-serif", "Plummelo", "navy", "white", "#dddddd", "gray", "black", true, true, true, true, false);
   
}

Plumelo.approveBetaInvitation = function(url,value,id){
	$('spinner').show();
 	new Ajax.Request(url.href ,{
 		methods: 'put',
 		parameters:{'_method':'put', 'beta_invitation[status]':value },
 		asynchronus: true,
 		onComplete: function(response){
			$('spinner').hide();
			url.innerHTML = "Approved";
            $(id).highlight();
			$(id).fade();
			}
 	})
}

Plumelo.removeIngredient = function(user_id,bookmark_id,ingredient_id,ing)
{      if(confirm("Are you sure you want to remove this ingredient ?")) 
		new Ajax.Request("/users/" + user_id + "/bookmarks/" + bookmark_id + "/delete_ingredient/" + ingredient_id ,{
 		methods: 'put',
 		parameters:{'authenticity_token':$('token').value},
 		asynchronus: true,
 		onComplete: function(response,transport){
			$('flash').innerHTML = response.responseText;
			$('flash').show();
			Plumelo.RemoveHeadersIfNoIngredientsExists();
			Modalbox.resizeToContent();
			 }
 	})
	else{
		return false;
	}
}
Plumelo.setResultsCountsAndRefine = function(){
	$('results_counts_area').innerHTML = $('results_counts').innerHTML;
}
Plumelo.validateAddingItem = function(){
   if($('added_shopping_item_name').value=='Add other shopping item'  ||  $('added_shopping_item_name').value.strip()==''){
		alert('Please enter the item name.');
		return false;
	}
   return true;	
}
function searchKeywordsFocus(t){
    if (t.value == 'Enter search keywords, Seperate with space.') {
        t.value = '';
    }
}

function searchKeywordsBlur(t){
    if (t.value == '') {
        t.value = 'Enter search keywords, Seperate with space.';
    }
}

function addOtherShoppingItemsFocus(t){
    if (t.value == 'Add other shopping item') {
        t.value = '';
    }
}

function addOtherShoppingItemsBlur(t){
    if (t.value == '')
       t.value = 'Add other shopping item';
}	
function checkedPublicRadioButton(){
    document.getElementById("bookmark_is_private_0").checked = true;
    Modalbox.hide();return false;
}
function AlreadyInPlanConfirmation()
{
	Modalbox.show($('alreadyinplan'), {title: this.title  , width:570}); return false;
	
}
function hideReplaceContains()
{
	document.getElementById('replace_contains').style.visibility = 'hidden';
	document.getElementById('recipe_user').style.visibility = 'visible';  
}
function searchTagsFocus(t){
	if (t.value == 'Enter Tag(s)') {
          t.value = '';
   }
}
function searchTagsBlur(t){
	if (t.value == '') {
      t.value = 'Enter Tag(s)';
  }
}

function addParameter(span_id, detail_id, rule_id)
{		
		var p = document.getElementById(span_id);
		if (p){
		      alert("You have already added this parameter in the Rule.")
		}else
    		{
    		new Ajax.Request("/images/select_parameter/", {
     		methods: 'post',
     		asynchronus: true,
     		parameters:{'authenticity_token':$('token').value, 'id': detail_id, 'rule_id': rule_id}
         })
 	}
}
