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


// Stats Reporting Calls
// var dispatcher=new com.mtvi.reporting.Dispatcher();
// var path = location.pathname.length>1?location.pathname.substring(1):"index.html";
// var channel = path.split("/").length>2?path.split("/")[1]:"";
// dispatcher.setAttribute('channel',channel);
// dispatcher.setAttribute('pageName',path);
// dispatcher.setAttribute('hier1',path);
// dispatcher.sendCall();

/* Please write callback function before calling metacafe.flash.js */
function processPlayerEvent(params){
	switch(params.eventName){
		case 'uploadComplete':
			$('finalize-video-form').submit();
			break;
		case 'sendToFriend':
			window.location="mailto:?subject=Check this out!&body=http://www.metacafe.com/watch/"+params.callbackParam;
			break;
		default:
			break;
	}
}

// Method: display_login
function display_login(b) {
	if(b) {
		Effect.Appear('pop-login', {duration: .4})
		setTimeout("$('username').focus()", 500);
	} else {
		Effect.Fade('pop-login', {duration: .6});
	}
}

function display_help(id, do_event) {
	if(do_event == "appear") {
		Effect.Appear(id, {duration: .4})
	} else {
		Effect.Fade(id, {duration: .6});
	}
}

function display_pop(id, b) {
	if(b) Effect.Appear('pop-' + id, {duration: .4})
  else Effect.Fade('pop-' + id, {duration: .6})		
}

function promote() {
  new Lightbox.base('goowy')
}

function detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}

// Browser detection
var BrowserDetect = {
  init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS";},
  searchString: function (data) { for (var i=0;i<data.length;i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity;} else if (dataProp) return data[i].identity;}}, 
  searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index+this.versionSearchString.length+1));}, dataBrowser: [ { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb"}, { string: navigator.vendor, subString: "Apple", identity: "Safari"}, { prop: window.opera, identity: "Opera"}, { string: navigator.vendor, subString: "iCab", identity: "iCab"}, { string: navigator.vendor, subString: "KDE", identity: "Konqueror"}, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox"}, { string: navigator.vendor, subString: "Camino", identity: "Camino"}, { string: navigator.userAgent, subString: "Netscape", identity: "Netscape"}, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE"}, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv"}, { string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla"} ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows"}, { string: navigator.platform, subString: "Mac", identity: "Mac"}, { string: navigator.platform, subString: "Linux", identity: "Linux"}]
}
BrowserDetect.init()
if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version < 6) window.location = 'unsupported_browser.html'




function not_to_miss(id, act, title, img, loc) {
	ntms = $$('#not-to-miss-list li');
	if(act == 'remove') {
		Element.remove('item-'+id);
	} else {
		var clear = true;
		
		if(ntms.length >= 10) {
			clear = false;
			msg = 'You may only select 10 Videos Not to Miss!';
		}
		
		if(clear) {
			ntms.each(function(n) {
				if(n.id == 'item-'+id) {
					clear = false;
					msg = 'That miss is already in the Videos Not to Miss!';
				}
			});
		}
		
		if(clear) {
			html = '<li id="item-'+id+'"><div class="thumb"><img width="90" height="76" src="'+img+'"/></div><dl><dt><a href="#">'+title+'</a></dt></dl><a class="action delete" onclick="if(confirm(\'Are you sure?\')) not_to_miss('+id+',\'remove\'); return false;" href="#">Remove</a><input id="ntm_ids[]" type="hidden" value="'+id+'" name="ntm_ids[]"/></li>';
			new Insertion.Bottom('not-to-miss-list', html);			
		} else {
			alert(msg);
		}		
	}
}


function handpicked(id, act, id_num, img, loc) {
	
	items = $$('#handpicked-list li');
	if(act == 'remove') {
		
		Element.remove('item-'+id);
	} else {
		
		var clear = true;
		
		if(items.length >= 5) {
			clear = false;
			msg = 'You may only handpick 5 Members a show.';
		}
		
		if(clear) {
			items.each(function(n) {
				if(n.id == 'item-'+id) {
					clear = false;
					msg = 'Member is already handpicked for show.';
				}
			});
		}
		
		img = img.gsub("/public","");
		
		if(clear) {
			html  = '<li id="item-'+id+'">';
			html += '<div class="thumb"><a href="/people/'+id+'"><img src="'+img+'" /></a></div>';
			html += '<dl class="user_info"><dt><a href="/people/'+id+'">'+id+'</a></dt><dd>'+loc+'</dd></dl>';
			html += '<div>';
			html += '<a class="action delete" href="#" onclick="handpicked(\''+id+'\', \'remove\'); return false;">Remove</a>';
			html += '</div>'
			html += '<input type="hidden" name="handpicked_ids[]" value="'+id_num+'">';
			html += '</li>';
			
			new Insertion.Bottom('handpicked-list', html);
			
		} else {
			alert(msg);
		}
	}
}


var Hotlist = {
	update: function(elem){		
		new Ajax.Request(sorter_url,{
			asynchronous: true,
			evalScripts:  true,
			method:       'put',
			parameters:   'hotlist=' + Sortable.sequence('hotlist'),
			onComplete: function(){
				elems = $$('#hotlist .hl_s');
				for(x = 0; elem = elems[x]; x++){
					elem.down().update(x + 1);
				}
			}
		});
	},
	createSorter: function(){
		Sortable.create('hotlist',{
			tag: 'li',
			only: 'hl_s',
			onUpdate: Hotlist.update
		});
	}
}

widget_in_use = false;

function scrollPhotoWidget(obj_id, distance) {
	if(!widget_in_use) { 
		obj = $(obj_id);
		if((distance >= 0 && obj.offsetLeft < 0) || (distance < 0 && obj.offsetLeft > -obj.offsetWidth - 5 * distance)) {
			widget_in_use = true; 
			new Effect.Move(obj_id, {x:distance, duration:.5, afterFinish:function(e){ widget_in_use = false; } });
		}
	}
}

function advancePhotoWidget(obj_id, increment, current_index) {
	widget_in_use = true;
	obj = $(obj_id);
	distance = current_index * increment;
	while(distance != 0) {
		if((distance >= 0 && obj.offsetLeft < 0) || (distance < 0 && obj.offsetLeft > - obj.offsetWidth - 5 * distance)) {
			new Effect.Move(obj_id, {x:distance, duration:.5, afterFinish:function(e){ widget_in_use = false; } });
			return;
		}
		distance -= increment
	}
}



/* Used for the color picker */
function update_colors(form_obj, field, form_id, hex_value, preview_id)
{
	
  field_name = form_obj + "_" + field;
  current_id = field_name + "_current";
  pickbtn_id = field_name + "_picker";
	
	$(field_name).value = hex_value;

  $(current_id).style.background = hex_value;
  $(pickbtn_id).style.background = hex_value;
	if(preview_id != ""){ $(preview_id).style.color = hex_value; }
}

/* This sets the field to the current selected color, it also updates current
 color boxes for visual feedback, created by Mark Malawski */
function update_colors_input(form_obj, field, form_id, preview_id)
{
	field_name = form_obj + "_" + field
	new_color = $(field_name).value
	current_id = field_name + "_current"
	pickbtn_id = field_name + "_picker"
	
	$(current_id).style.background = new_color
	$(pickbtn_id).style.background = new_color
	if(preview_id != ""){ $(preview_id).style.color = new_color; }
}


// Takes in image_id, parses it to get the preview_id for that image select
function get_preview_id(image_id, form_id)
{
	
	form_prefix = form_id + "_";
	
	image_id = image_id.gsub("_profile_idle_img","");
	image_id = image_id.gsub("_profile_over_img","");
	image_id = image_id.gsub(form_prefix,"");
	image_id = image_id + "_pic";
	
	return image_id;
}


// Checks if value is set to default, if so don't set the value to default, instead grab
// the default value from a js variable since the js variable can be changed when selecting
// a new default
function default_check(value, default_select_id)
{
	
	var new_value;
	
	if(value=="Default")
	{
		new_value = $(default_select_id).value;
	} else {
		new_value = value;
	}
	
	return new_value;
}


// Main function to update the preview with each font_select
function font_select_onchange(preview_id, field_id, value, default_font)
{
	if(value != "Default")
	{
		$(preview_id).style.fontFamily=value;
		$(field_id).value=value;
	} else {
		$(preview_id).style.fontFamily=default_font;
		$(field_id).value=value;
	}
}


// If the default font is changed, update the previews for all font selects set to use default
function update_default_font_selects(value)
{
	
	var font_selects = document.getElementsByClassName("default_font");
	
	$A(font_selects).each(function(e){
		var header_id = e.id.gsub("_font_select","") + "_header_preview";
		
		$(header_id).style.fontFamily=value;
	});
	
}


// If the default font color is changed, update the previews for all font colors set to use default
function update_default_font_colors(value)
{
	//alert($('show_default_header_color_palette').down(0).down(0).next(0).readAttribute("id"))
	var color_pickers = document.getElementsByClassName("default_color");
	
	$A(color_pickers).each(function(e){
		
		plain_id = e.readAttribute("id").gsub("show_","").gsub("_color_picker","");
		id = "show_" + plain_id + "_color";
		preview_id = plain_id + "_preview";
		
		set_value_to_default(id, value, preview_id);
	})
}


// Switches class of font_select depending on if it is set to default or not.
function class_switch_font_select(self)
{
	if (self.value == "Default")
	{
		self.className="font_select default_font"
	} else {
		self.className="font_select";
	}
}

// 
function set_value_to_default(id, default_value, preview_id)
{
	var picker_id = (id + "_picker");
	var current_id = (id + "_current");
	var default_img = "/images/admin/icons/d_icon.gif";
	
	$(picker_id).style.backgroundColor=default_value;
	$(current_id).style.backgroundColor=default_value;
	$(picker_id).addClassName("default_color");
	$(preview_id).style.color=default_value;
}

// Updates Profile Thumb Previews background with selected background color
function update_preview_background_colors(id)
{
	// Not needed, may be needed in the future
	// var color = $(id).value;
	// var profile_previews = document.getElementsByClassName("profile_thumbs_admin");
	// 
	// $A(profile_previews).each(function(e){
	// 	e.style.backgroundColor=color;
	// })
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}




// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}	




// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}




function remove_cookie(name,path,domain){
	if (Get_Cookie(name))
	{
		Delete_Cookie(name,path,domain);
	}
}



/* hides background repeat field if no background image is selected */
function bg_repeat_field_toggle(bg_type)
{
	var image_selector = 'show_'+ bg_type +'_background_image';
	var repeat_selector = bg_type + '_background_image_repeat_field';
	
	if($(image_selector).value == "None"){
		$(repeat_selector).style.display='none';
	}else{
		$(repeat_selector).style.display='';
	}
}


/* Takes in a image select preview id and the value of a drop down containing background 
repeat options and updates background position of the preview */
function update_image_select_preview(is_id,value)
{
	var css_repeat;
	var css_position = "top left";
	
	if(value=="none"){ css_repeat = "no-repeat"; }
	if(value=="repeat"){ css_repeat = "repeat"; }
	if(value=="across_top"){ 
		css_repeat = "repeat-x";
		css_position = "top";
	}
	if(value=="across_bot"){ 
		css_repeat = "repeat-x";
		css_position = "bottom";
	}
	
	$(is_id).style.backgroundRepeat=css_repeat;
	$(is_id).style.backgroundPosition=css_position;
}


/* Returns the value of the selected radio button in the radio group, null if 
none are selected, and false if the button group doesn't exist */
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}


/* Updates sponsor text/images in upload videos section. Will show/hide 
certain elements depending on passed in flux category id */
function update_sponsor(category_id)
{
	$('sponsor_images').select('span').each(function(e){
		e.style.display="none";
	});
	
	$('sponsor_texts').select('span').each(function(e){
		e.style.display="none";
	})
	
	if($(category_id + '_image'))
	{
		$(category_id + '_image').style.display="";
	}
	
	if($(category_id + '_text'))
	{
		$(category_id + '_text').style.display="";
	}

}