/*-----------------------------------------------------------------
	
	Application.js
	Updated: 2008/02/12
	Author: 
	
-----------------------------------------------------------------*/

var Rouxbe = {};

Rouxbe.Tabs = {	
	show_tab: function(tab_name, array) {
		Rouxbe.Tabs.hide_all_tabs(array)
		$(tab_name+"_content").show();
		$(tab_name+"_tab").addClassName("active")
	},
	hide_all_tabs: function(array) {
		array.each(function(el){
			tab = $(el+"_tab")
			content = $(el+"_content")
			
			if(tab){tab.removeClassName("active")}
			if(content){ content.hide();}
		})
	}	
}

Rouxbe.ContactForm = {
  validate: function(form) {
  	name = form.elements["contact[name]"];
  	company = form.elements["contact[company]"];
  	email = form.elements["contact[email]"];
  	message = form.elements["contact[message]"];

  	if ($("name_field_error"))
  		Element.remove($("name_field_error"));
  	if ($("email_field_error"))
  		Element.remove($("email_field_error"));
  	if ($("message_field_error"))
  		Element.remove($("message_field_error"));

  	if (name.value == "") {
  		if (!$("name_field_error")) {
  			new Insertion.After("contact_name_field", "&nbsp;<span style=\"display:none;\" id=\"name_field_error\" class=\"errors\">Please don't forget to tell us your name.</span>");
  		} else {
  			$("name_field_error").display = "none";
  		}
  		new Effect.Appear("name_field_error");
  		name.focus();
  		return false;
  	}

  	if (email.value != "") {
  		if (email.value.indexOf("@") == -1 || email.value.indexOf(".") == -1) {
  			if (!$("email_field_error")) {
  				new Insertion.After("contact_email_field", "&nbsp;<span style=\"display:none;\" id=\"email_field_error\" class=\"errors\">Please enter a valid email address</span>");
  			} else {
  				$("email_field_error").display = "none";
  			}
  			new Effect.Appear("email_field_error");
  			email.focus();
  			return false;
  		}

  	}

  	if (message.value == "") {
  		if (!$("message_field_error")) {
  			new Insertion.After("contact_message_field", "&nbsp;<span style=\"display:none;\" id=\"message_field_error\" class=\"errors\">Please don't forget to give us your message.</span>");
  		} else {
  			$("message_field_error").display = "none";
  		}
  		new Effect.Appear("message_field_error");
  		message.focus();
  		return false;
  	}
  	return true;
  }
}

/*-----------------------------------------------------------------

	Rouxbe Utilities

-----------------------------------------------------------------*/
Rouxbe.Utils = {	
	selectAll: function(id) {
		$(id).focus();
    $(id).select();
	},
	
	show_hide: function(element, word_replace){
		element.toggle();
		word_replace.innerHTML = (element.getStyle('display') != "none") ? "Hide" : "Show"
	},
	
	show_hide_image: function(element, a_element) {
		element.toggle();
		src = (element.getStyle('display') != "none") ? "/images/bio_arrowclose.gif" : "/images/bio_arrowopen.gif"
		a_element.down("img").writeAttribute("src", src)
	},
	
	windowLocation: function(url) {
		//alert("GOTO => "+url)
		window.location.href = url;
	},

  // toggles expand/collapse state for a tree node
	toggleTreeNode: function(page_id, node_id) {
	  element = $(node_id + '-child');
	  parent_el = $(node_id + '-parent');
	  if (element.visible()) {
			element.hide();
			parent_el.addClassName('close');
			parent_el.removeClassName('open');
			Rouxbe.Utils.storeTreeNodeState(page_id, node_id, 'collapsed')
	  } else {
			element.show();
			parent_el.addClassName('open');
			parent_el.removeClassName('close');
			Rouxbe.Utils.storeTreeNodeState(page_id, node_id, 'expanded')
	  }
	},
	
	// persists a treeNode's collapse/expand state using cookies
	storeTreeNodeState: function(page_id, node_id, new_state) {
		c = Cookie.get(page_id);
		c = c ? c.evalJSON() : [];
		if ('collapsed' == new_state) {
			c = c.without(node_id);
		} else if ('expanded' == new_state) {
			c.push(node_id);
			c = c.uniq();
		}
		Cookie.set(page_id, c.toJSON(), 2);
	},

	// restores al treeNodes' collapse/expand state using cookies
	restoreTreeNodeStates: function(page_id) {
		node_ids = Cookie.get(page_id);
		if (node_ids) {
			node_ids = node_ids.evalJSON();
			node_ids.each(function(node_id) {
				Rouxbe.Utils.toggleTreeNode(page_id, node_id);
			})
		}
	}
}

/*-----------------------------------------------------------------

	Rouxbe Rating Methods

-----------------------------------------------------------------*/
Rouxbe.Rating = {
	
	UPDATING:	 		"Updating ...",
	FULL_TEXT:		"<span class='percentage'>#{number}%</span> - <span class='quote'>#{text}</span>",
	YOUR_RATING:	"Your Success Rating: <strong>#{number}</strong>%",
	TEXT: 				[
								"I fed it to the dog",
								"It did not turn out well",
								"It was below average",
								"It was okay, might try it again",
								"It was really good",
								"It turned out exactly as hoped."
								],
	
	create: function(class_name, id, value) {
		$("track-"+id+"-help").innerHTML = this.UPDATING;
		new Ajax.Request('/ratings', 
										{asynchronous:true, evalScripts:true, method:'post', 
										parameters: {"rateable_type" : class_name, "rateable_id" : id, "rating" : value}, 
										onComplete:function(transport){ Rouxbe.Rating.saved(id, value) }})
	},
	
	saved: function(id, value) {
		$("track-"+id+"-help").innerHTML = this.YOUR_RATING.interpolate({number: value})
	},
	
	help: function(id, value) {
		// The value is between 0-100
		// We want it to be between 0-5
		var index = (((value/20).floor())*20)/20
		if(this.TEXT[index] != null)
		{
			$("track-"+id+"-help").innerHTML = this.FULL_TEXT.interpolate({number: value, text: this.TEXT[index] })
			$("track-"+id+"-help").show();
		}
		else
		{
			$("track-"+id+"-help").hide();
		}
	}
}


/*-----------------------------------------------------------------

	Rouxbe Printing Methods

-----------------------------------------------------------------*/
Rouxbe.Print = {
	Recipe: function() {
		if($('recipedetails_contents') != null){
			showTextRecipe()
		};
		window.print();
	}
}


/*-----------------------------------------------------------------

	Rouxbe CSS Methods

-----------------------------------------------------------------*/
Rouxbe.Css = {
	screen_sheets: 	null,
	print_sheets: 	null,
	active: 				null,
	
	SetPrint: function(arr) {
		print_sheets = arr
	}, 
	
	SetScreen: function(arr) {
		screen_sheets = arr
	},
	
	Print: function() {
		if($('recipedetails_contents') != null){
			showTextRecipe()};
		
		for(i=0; i<screen_sheets.length; i++) {
			if($(screen_sheets[i]) != null){
			$(screen_sheets[i]).disabled = true};
		}
		for(i=0; i<print_sheets.length; i++) {
			if($(print_sheets[i]) != null){
			$(print_sheets[i]).disabled = false};
		}
		active = "print"
	},
	
	Screen: function() {
		for(i=0; i<screen_sheets.length; i++) {
			if($(screen_sheets[i]) != null){
			$(screen_sheets[i]).disabled = false;}
		}
		for(i=0; i<print_sheets.length; i++) {
			if($(print_sheets[i]) != null){
				$(print_sheets[i]).disabled = true};
		}
		active = "screen"
	},
	
	Toggle: function() {
		(active == "print")?this.Screen():this.Print();
	}
}


/*-----------------------------------------------------------------

	Rouxbe Player Methods

-----------------------------------------------------------------*/
var PreviewPlayer = {
	openPrintRecipe: function(recipe_id) {
		Rouxbe.Utils.windowLocation("/recipes/"+recipe_id+";text")
	},
	openGallery: function() {
		Rouxbe.Utils.windowLocation("/recipes")
	},
	openFullRecipe: function(user_type_id, recipe_id) {

		// Logged in user
		if (user_type_id == 1) {
			Rouxbe.Utils.windowLocation("/recipes/"+recipe_id)
		}
		// Invited via Invite a friend
		else if (user_type_id == 2) {
			Rouxbe.Utils.windowLocation("/viewer/tellfriend/"+recipe_id)
		}
	}
}

var TopicForm = {
  editNewTitle: function(txtField) {
    $('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var LoginForm = {
  setToPassword: function() {
    $('openid_fields').hide();
    $('password_fields').show();
  },
  
  setToOpenID: function() {
    $('password_fields').hide();
    $('openid_fields').show();
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    $('edit-post-' + postId + '_spinner').show();
    this.clearReplyId();
  },

  // sets the current post id we're editing
  setReplyId: function(postId) {
    $('edit').setAttribute('post_id', postId.toString());
    $('post_' + postId + '-row').addClassName('editing');
    if($('reply')) $('reply').hide();
  },
  
  // clears the current post id
  clearReplyId: function() {
    var currentId = this.currentReplyId()
    if(!currentId || currentId == '') return;

    var row = $('post_' + currentId + '-row');
    if(row) row.removeClassName('editing');
    $('edit').setAttribute('post_id', '');
  },
  
  // gets the current post id we're editing
  currentReplyId: function() {
    return $('edit').getAttribute('post_id');
  },
  
  // checks whether we're editing this post already
  isEditing: function(postId) {
    if (this.currentReplyId() == postId.toString())
    {
      $('edit').show();
      $('edit_post_body').focus();
      return true;
    }
    return false;
  },
  
  

  // close reply, clear current reply id
  cancel: function() {
    this.clearReplyId();
    $('edit').hide()
  }
}

var ReplyForm = {
  // yes, i use setTimeout for a reason
  init: function() {
    EditForm.cancel();
    $('reply').toggle();
    $('post_body').focus();
    // for Safari which is sometime weird
//    setTimeout('$(\"post_body\").focus();',50);
  }
}

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

function back()
{
	history.go(-1)
}

function disable(id)
{
	$$("div#recipe_"+id+" div.bg").each(function(e){
		e.addClassName('disabled')
	});
}



/*
Makes 32 bit PNG's transparency work in Internet Explorer 6
 * Dependent on Prototype 1.6
 * Works on img elements and on background images of elements
 * Image tiling will not work
 * Refer to the readme

Example Usages:
 
 $('yourPNG').pngHack();
 $$('div#fixMe', 'img#andMe', 'img.andUsTo').invoke('pngHack');
 
*/
Element.addMethods({
  pngHack: function(el){
    var el = $(el);
    var transparentGifPath = '/images/transparent.gif';
    if (Prototype.Browser.IE){
      /* if it's an img and a png */
      if ((el.match('img')) && (el.src.include('png'))){
        var alphaImgSrc = el.src;
        var sizingMethod = 'scale';
        el.src = transparentGifPath;
        /* if it's an element with a background png */
      } else if (el.getStyle('backgroundImage').include('png')){
        var bgColor = el.getStyle('backgroundColor') || '';
        var elBg = el.getStyle('backgroundImage');
        var alphaImgSrc = elBg.slice(5, elBg.length - 2);
        var sizingMethod = 'crop';
        el.setStyle({ 'background': bgColor + transparentGifPath });
      }

      if (alphaImgSrc) {
				el.runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="#{al}",sizingMethod="#{sz}")'.interpolate({ al: alphaImgSrc, sz: sizingMethod });
			}
    }
    return el;
  }
});

/*-----------------------------------------------------------------

	Rouxbe Analytics Methods
	
	Any link with CSS class 'tracked' will be run through our app
	for tracking and then redirected

-----------------------------------------------------------------*/
// TODO: change to regex to track all outgoing links, no css class required
Rouxbe.Analytics = {
  processTrackedUrls: function() {
    $$('a.tracked').each ( function(anchor) {
      anchor.href = '/r/' + encodeURIComponent(anchor.href)
    });
  }
}
Event.observe(window, 'load', function() {
  Rouxbe.Analytics.processTrackedUrls();
});

/*-----------------------------------------------------------------

  Rouxbe SWFObject overrides
  
  To take care of the player "Mushroom" bug/
  We hide the player when we first render it and don't show it until
  we call the so.write method.
  
  This is a wrapper around the so.write method where we first
  reveal our player

-----------------------------------------------------------------*/
Rouxbe.SWFObject = {
  write: function(dom_id, swf_object) {
    $(dom_id).show();
    swf_object.write(dom_id);
  }
}
