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

/* OPEN POPUP */
function openWindow(url, width, height) {
  w = window.open(url, "popupWindow", "width=" + width + ", height=" + height + ", location=1, scrollbars=1, resizable=1, status=0");
  w.focus();
}

/* Application menu drop down */
function showAppsDropdown(yOffset) {
  e1 = Element.makePositioned('applications-link');
  pos = Element.positionedOffset(e1);
  newTop = pos["top"] + yOffset;
  $('apps-drop-down').setStyle({ top: newTop + "px", left: pos["left"] + "px"});
  new Effect.BlindDown('apps-drop-down', { duration:0.3, afterFinish:function(e) { Event.observe(document, 'mousemove', hideAppsDropdown) } });
}

function hideAppsDropdown(e) {
  mouseX = Event.pointerX(e);
  mouseY = Event.pointerY(e);
  
  positionedElement = Element.makePositioned('apps-drop-down');
  containerPosition = Element.cumulativeOffset(positionedElement);
  containerDimensions = Element.getDimensions('apps-drop-down');
  
  if (mouseX < containerPosition["left"] || mouseX > (containerPosition["left"] + containerDimensions["width"]) ||
      mouseY < (containerPosition["top"] - 30) || mouseY > (containerPosition["top"] + containerDimensions["height"])) {
      Element.hide('apps-drop-down');
      Event.stopObserving(document, 'mousemove', hideAppsDropdown);
  }
}

/* End application menu drop down */

function openThickbox(title, url, width, height) {
  tb_show(title, url+'?width='+width+'&height='+height + "&KeepThis-true&TB_iframe=true", false);
}

/* FORM HELPERS */
function show_info(field_name) {
  if ($(field_name + '-notice').innerHTML == "")
    $(field_name + '-notice').innerHTML = "<div class='info-icon'><img src='/images/icons/icon_info.gif' /></div><div class='info-text'>" + arrayInfo[field_name] + "</div>";
}

function clear_info(field_name) {
  $(field_name + '-notice').innerHTML = "";
}

function div_swap(field1, field2)
{
	if ($(field1).style.display == 'none') {
		Element.hide(field2);
		new Effect.Appear(field1);
	}
	else
	{
		Element.hide(field1);
		new Effect.Appear(field2);
	}
}

function div_fade(field, focus_field)
{
	if ($(field).style.display == 'none') 
	  if (!focus_field)
		  new Effect.Appear(field, { duration:0.5 });
		else
		  new Effect.Appear(field, { duration:0.5, afterFinish:function(e) { $(focus_field).focus(); }});
	else
		Element.hide(field);
}

function div_slide(field)
{
	if ($(field).style.display == 'none') 
		new Effect.SlideDown(field);
	else
		Element.hide(field);
}

function checkAll(frm, name_prefix, bool_on_off) {
  for(i=0;i<frm.length;i++) {
    e=frm.elements[i];
    if (e.type == "checkbox" && (e.name).substring(0,name_prefix.length) == name_prefix) {
      e.checked = bool_on_off;
    }
  }
}

function toggleEditLink(cancelLinkContainer, editLinkContainer, editBox, mainContent)
{
  if ($(editLinkContainer).style.display == 'none')
  {    
    Element.hide(cancelLinkContainer);
    Element.show(editLinkContainer);
    
    new Effect.Fade(editBox, { duration:0.3, afterFinish:function(e) {
      new Effect.Appear(mainContent, { duration:0.1, afterFinish:function(e) { 
        Element.hide(editLinkContainer + "-loading") 
      }});   
    }});
  }
  else
  {
    new Effect.Fade(mainContent, { duration:0.3, afterFinish:function(e) {
      new Effect.Appear(editBox, { duration:0.1, afterFinish:function(e) { 
        Element.hide(editLinkContainer);
        Element.show(cancelLinkContainer);
        Element.hide(editLinkContainer + "-loading") 
      }});   
    }});   
  }
}


function setPlaceHolder(textbox) {
	if (textbox.value == '') {
  	textbox.style.color = "#707070";
  	textbox.value = textbox.title;
	} else if (textbox.value != textbox.title) {
		textbox.style.color = "#000";
	}
}

function clearPlaceHolder(textbox) {
  if (textbox.value == textbox.title) {
    textbox.value = '';
    textbox.style.color = "#000";
  }	
}

function checkPlaceHolder(textbox) {
	if (textbox.value == textbox.title) {
    textbox.value = '';
  }
}

function swapSearchForms(hide,show,radio)
{
  Element.hide(hide);
  Element.show(show);
  $(radio).checked = true;
}

/* END FORM HELPERS */

/* Content Rating */
var rateHandler;
var rateClickHandler;

function toggleRatingHover(obj_class, obj_id, iconIndex, num_icons)
{  
  hoverBox = $('ratings-hover-container');
  if (hoverBox == null) return;
  
  currBox = $(obj_class.toLowerCase() + "-ricon-" + obj_id);
  pos = currBox.cumulativeOffset();
  
  hoverBox.setStyle({ top: pos["top"] + "px", left: pos["left"] + "px"})
  hoverBox.show();
  for (i=1;i<=iconIndex;i++) {
    Element.show("rating-hover-temp-" + i);
  }
  clearHandlers();
  rateHandler = hideHoverIcons.bindAsEventListener(this, obj_class, obj_id, iconIndex, num_icons);
  rateClickHandler = submitRating.bindAsEventListener(this, obj_class, obj_id, iconIndex, num_icons);
  Event.observe(document, 'mousemove', rateHandler);
  Event.observe($("ratings-hover-container"), 'click', rateClickHandler);
}

function hideHoverIcons(e, obj_class, obj_id, iconIndex, num_icons) {
  mouseX = Event.pointerX(e);
  mouseY = Event.pointerY(e);

  currIcon = $(obj_class.toLowerCase() + "-rh-" + obj_id + "-" + iconIndex);
  pos = currIcon.cumulativeOffset();
  dim = currIcon.getDimensions();
  actualLeft = parseInt(pos["left"]) - parseInt(currIcon.getStyle("padding-left").replace("px", "")) - parseInt(currIcon.getStyle("margin-left").replace("px", ""))
  actualWidth = parseInt(dim["width"]) + parseInt(currIcon.getStyle("padding-left").replace("px", "")) + parseInt(currIcon.getStyle("margin-left").replace("px", "")) +
                parseInt(currIcon.getStyle("padding-right").replace("px", "")) + parseInt(currIcon.getStyle("margin-right").replace("px", ""))

  if (mouseX < actualLeft || mouseX > (actualLeft + actualWidth) ||
      mouseY < pos["top"] || mouseY > (pos["top"] + dim["height"])) {
    Element.hide('ratings-hover-container');
    for (i=1;i<=num_icons;i++) {
      Element.hide("rating-hover-temp-" + i);
    }
    clearHandlers();
  }
}

function submitRating(e, obj_class, obj_id, iconIndex, num_icons) {
  clearHandlers();
  authToken = $('ratings-auth').innerHTML;
  Element.hide(obj_class.toLowerCase() + "-ricon-" + obj_id);
  Element.show(obj_class.toLowerCase() + "-rnote-" + obj_id);  
  new Ajax.Updater(obj_class.toLowerCase() + "-rating-box-" + obj_id, "/rate_five/" + obj_class + "/" + obj_id + "/" + iconIndex,
                   { asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent(authToken) });
  for (i=1;i<=num_icons;i++) {
    Element.hide("rating-hover-temp-" + i);
  }
  return false;
}

function clearHandlers() {
  if (rateHandler != null) {
    Event.stopObserving(document, 'mousemove', rateHandler);
    rateHandler = null;
  }
  if (rateClickHandler != null) {
    Event.stopObserving($("ratings-hover-container"), 'click', rateClickHandler);  
    rateClickHandler = null;
  }
}

function rateUpDown(obj_class, obj_id, path, auth_token) {
  Element.hide(obj_class + "-ticon-" + obj_id);
  Element.show(obj_class + "-tnote-" + obj_id);
  new Ajax.Updater(obj_class + "-thumbs-box-" + obj_id, path, {asynchronous:true, evalScripts:true, parameters:'authenticity_token=' + encodeURIComponent(auth_token)});
  return false;
}

function showBelowThreshold(obj_class, obj_id, show) {
  if (show) {
    if ($(obj_class + '-below-threshold-' + obj_id) != null) Element.hide(obj_class + '-below-threshold-' + obj_id);
    Element.show(obj_class + '-ticon-' + obj_id);
    Element.show(obj_class + '-body-' + obj_id); 
    msg_div = $(obj_class + '-bt-msg-' + obj_id);
    if (msg_div != null) msg_div.hide();
  } else {
    if ($(obj_class + '-below-threshold-' + obj_id) != null) Element.show(obj_class + '-below-threshold-' + obj_id);
    Element.hide(obj_class + '-ticon-' + obj_id);
    Element.hide(obj_class + '-body-' + obj_id);
    msg_div = $(obj_class + '-bt-msg-' + obj_id);
    if (msg_div != null) msg_div.show();    
  }  
}

/* End Content Rating */


/* DATE HELPERS */
function isValidDate(month,day,year) {
	res = Array();

  /* MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY */
	if (month < 1 || month > 12) { /* check month range */
		res = [ "false", dateHelperArrayInfo['month_check1'] ];
	}
	else if (day < 1 || day > 31) {
		res = [ "false", dateHelperArrayInfo['day_check'] ];
	}
	else if ((month==4 || month==6 || month==9 || month==11) && day==31) {
	  if (month==4) month = dateHelperArrayInfo['month_apr'];
	  if (month==6) month = dateHelperArrayInfo['month_jun'];
	  if (month==9) month = dateHelperArrayInfo['month_sept'];
	  if (month==11) month = dateHelperArrayInfo['month_nov'];
	  
		res = [ "false", dateHelperArrayInfo['month_check2'].replace("<month>", month) ];
	}
	else if (month == 2) { /* check for february 29th */
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			res = [ "false", dateHelperArrayInfo['month_check3'].replace("<year>", year).replace("<day>", day) ]
	  }
	}
	else {
		res = [ "true", dateHelperArrayInfo['date_ok'] ];		
	}

	return res;
}

/* END DATE HELPERS */

/* Helper function for download functionality */

function showImageDownload(title,url, width, height) {
height += 8;
tb_show(title, url+'?width='+width+'&height='+height, false)
}

function downloadVideo(url) {
	new Ajax.Request(url,{
		method:'get'
	}
		
)};

/* Popup window for flags on homepage */
function beta_signup(title,country){
	tb_show(title, "/beta_signup/index&?keepThis=true&width=372&height=510&country="+country, null);
}

/* Popup window for email feeder */
function showEmailFeeder(address) {
	address = address.replace("(at)","@");
	address = address.replace("(dot)",".");
	url = "/emailfeeder/new?recepient="+address+"&KeepThis-true&TB_iframe=true&width=356&height=515"
	tb_show(address, url, false);
}

var TBIntervalID = 0;

// resize thickbox to current contents
function resizeTB(runTimer) {
  if ($('tb-container') != null && parent.$('TB_iframeContent') != null) {
    dim = $('tb-container').getDimensions();
    if (dim.height > 50) {
      maxHeight = parent.document.viewport.getHeight() - 100;      
      newHeight = Math.min(dim.height, maxHeight);
      parent.$("TB_iframeContent").setStyle({height: newHeight + "px"});
      repositionTB(parent.$('TB_window'), 0, newHeight);
      clearInterval(TBIntervalID);
    } else if(runTimer) { // dimensions don't register correctly the first hit on some browsers so keep trying
      TBIntervalID = setInterval('resizeTB(false)', 100);
    }
  }
}

function repositionTB(tbwin, TB_WIDTH, TB_HEIGHT) {
  if (TB_WIDTH > 0) {
    if (tbwin) tbwin.setStyle({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});    
  }
  if (TB_HEIGHT > 0) {
    var version = (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
    if ( !(Prototype.Browser.IE && version < 7)) { // take away IE6
      if (tbwin) tbwin.setStyle({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
    }  
  }
  parent.TBCustomBordersInit();
}

function showFullScreenLoading(overlay) {
  dim = document.viewport.getDimensions();
  container = $(overlay);
  if (container != null) {
    w = dim['width'];
    h = dim['height'];
    
    $(overlay).style.width = w + "px";
    $(overlay).style.height = h + "px"; 

    scroll_offsets = document.viewport.getScrollOffsets();
    $(overlay).style.top = scroll_offsets.top + "px";
    $(overlay).style.left = scroll_offsets.left + "px";
    Element.show(overlay);
  }
}

//Report Abuse popUp Function
function openReportAbuseWindow(object_id, object_type, object_url) {
  tb_show('Report Abuse!', '/abuse_reports/new?' + 'object_id=' + object_id + '&object_type=' + object_type + '&object_url=' + object_url + '&KeepThis=true&TB_iframe=true&width=345&height=530', false) ;
}

function toggle_link(object_id, show, hide)
{
  if ($(object_id).style.display == ''){
    new Element.hide(object_id);
    $(object_id + '-switch').innerHTML = show
  } else {
    new Element.show(object_id)
    $(object_id + '-switch').innerHTML = hide
  }
}

/* CUSTOM EFFECTS */

Effect.SlideRightIn = function(element) {
/*
	SlideRightIn needs to have the content of the element wrapped in a container element with fixed width!
*/
	element = $(element).cleanWhitespace();
	var elementDimensions = element.getDimensions();
	return new Effect.Scale(element, 100, 
		Object.extend({ 
			scaleContent: false, 
			scaleY: false, 
			scaleFrom: window.opera ? 0 : 1,
			scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
			restoreAfterFinish: true,
			afterSetup: function(effect) {
				effect.element.makePositioned();
				effect.element.down().makePositioned();
				if(window.opera) effect.element.setStyle({left: ''});
				effect.element.makeClipping().setStyle({width: '0px'}).show(); 
			},
			afterUpdateInternal: function(effect) {
				effect.element.down().setStyle({right: (effect.dims[1] - effect.element.clientWidth) + 'px' }); 
			},
			afterFinishInternal: function(effect) {
				effect.element.undoClipping().undoPositioned();
				effect.element.down().undoPositioned();
			}
		}, arguments[1] || {})
	);
}

/* Used to slide out app drawer so it doesn't go all the way out */
Effect.SlideLeftOut = function(element) {
/*
	SlideLeftOut needs to have the content of the element wrapped in a container element with fixed width
	otherwise any text or images begin to wrap in stange ways!
*/
	element = $(element).cleanWhitespace();
	return new Effect.Scale(element, window.opera ? 0 : 1,
		Object.extend({ 
			scaleContent: false, 
			scaleY: false, 
			scaleMode: 'box',
			scaleFrom: 100,
			restoreAfterFinish: true,
			beforeStartInternal: function(effect) {
				effect.element.makePositioned();
				effect.element.down().makePositioned();
				if(window.opera) effect.element.setStyle({left: ''});
				effect.element.makeClipping().show();
			},  
			afterUpdateInternal: function(effect) {
				effect.element.down().setStyle(
					{right: (effect.dims[1] - effect.element.clientWidth) + 'px' }
				);
			},
			afterFinishInternal: function(effect) {
				effect.element.hide().undoClipping().undoPositioned();
				effect.element.down().undoPositioned();
			}
		}, arguments[1] || {})
	);
}

/* \CUSTOM EFFECTS */
