// need this for the AJAX responder for ratings
var current_rtg_dv = '';
var current_fv_dv = '';

/* Clearing/Showing default text */

function fieldDefFocus (inpt, dflt)
{
	inpt.value = (inpt.value == dflt) ? '' : inpt.value ;
}

function fieldDefBlur (inpt, dflt)
{
	inpt.value = (inpt.value == '') ? dflt : inpt.value ;
}

/* Ratings Handlers */

var old_rtg_html;

function mediaRating (mediaId, rating)
{
	parameters = {
		module: "Media",
        type: "ajax",
        func: "rate",
		media_id: mediaId,
		rating: rating
	};

	old_rtg_html = $('rtg_dv_' + mediaId).innerHTML;

	$('rtg_dv_' + mediaId).innerHTML = '<span class="size11" style="display: inline; height: 22px; width: 90px;">Saving...</span>';

	current_rtg_dv = 'rtg_dv_' + mediaId;

	var myAjax = new Ajax.Request(
		site_address + 'ajax.php',
		{
			method: 'post',
			parameters: parameters,
			onComplete: handleRatingResponse
		}
	);

	/*
	new Ajax.Updater(
		"rtg_dv_" + mediaId,
		site_address + 'ajax.php',
		{
			method: 'post',
			parameters: parameters
		}
	);
	*/
}

function handleRatingResponse(originalRequest)
{
	if ("-2" == originalRequest.responseText)
	{
		alert('You cannot rate your own media.');
		$(current_rtg_dv).innerHTML = old_rtg_html;
	}
	else
	{
		$(current_rtg_dv).innerHTML = originalRequest.responseText;
	}
}

function rtStrMO (media_id, rating, idx, mode)
{
	// hmmm not sure how we'll get to this var.
	// if (undefined != eval("rated_str_" + media_id)) { return false; }

	for (var i=((0<rating)?rating+1:1); i <= idx; i++)
	{
		imgid = 'rt_str_' + media_id + '_' + i;
		img = document.getElementById(imgid);
		img.src = site_address + "images_global/img_star_" + mode + "-trans.png";
	}
}

/* Favorites Handlers */

function mediaFavorite (mediaId, mediaType, fave)
{
	action = (1 == fave) ? 'addFavorite' : 'removeFavorite';

	parameters = {
	    module: "application",
        type: "ajax",
        func: action,
		media_id: mediaId,
		media_type: mediaType
	};

	$('fv_' + mediaId).innerHTML = '<span class="size10" style="display: inline; height: 22px; width: 90px;">Saving...</span>';

	current_fv_dv = 'fv_' + mediaId;

	var myAjax = new Ajax.Request(
		site_address + 'ajax.php',
		{
			method: 'post',
			parameters: parameters,
			onComplete: handleFavoriteResponse
		}
	);
}

function handleFavoriteResponse(originalRequest)
{
	$(current_fv_dv).innerHTML = originalRequest.responseText;
}

function submitProcessorForm(form_id)
{
	is_ok = true;
	Element.scrollTo('hd');
	
	is_ok = validateForm(form_id, false, false, false, true, 4);
	
	if(is_ok)
	{
		var processor_modal = new Control.Modal
		(
			'modal_window_text',
			{
				overlayCloseOnClick: false,
				width: 800,
				height: 350,
				contents: function() { return $('processor_window_contents').innerHTML; }
			} // end params
		);
		
		// processor_modal.href = 'http://www.google.com';
		processor_modal.open();
		return true;
	}
	
	return false;
}

function submitFbProcessorForm(form_id)
{
	var is_ok = true;
	is_ok = validateForm(form_id, false, false, false, true, 4);

	if(is_ok)
	{
		return true;
	}

	return false;
}
	

function submitProcessor(form_id)
{
	$(document.body).startWaiting('bigWaiting');
	return true;
}

/*** SHARE IT FUNCTIONS ***/
function showShareForm(media_id, form_type)
{
	if(!form_type)
	{
		var form_type = 'small';
	}
	
	var pars = 'module=media&type=ajax&func=getShareForm&mid=' + media_id + '&form_type=' + form_type;
	var myAjax = new Ajax.Updater
	(
		'share_' + media_id, 
		site_address + 'ajax.php',
		{
			method: 'post',
			parameters: pars,
			evalScripts: true,
			onComplete: function()
			{
				Effect.toggle('media_' + media_id, 'blind');
				Effect.toggle('share_' + media_id, 'blind');
			}
		}
	);
}

function doShareIt(media_id)
{
	var friend_id = '';
	var friend_email = '';
	
	if($('friend_id_' + media_id))
	{
		friend_id = $F('friend_id_' + media_id);
	}
	
	friend_email = $F('friend_email_' + media_id);
	
	if(friend_id == '' && friend_email == '')
	{
		alert('Please choose a friend or enter an email address to share');
		return;
	}
	
	var pars = 'module=media&type=ajax&func=sendMessage&' + Form.serialize('share_form_' + media_id) + '&mid=' + media_id;
	
	var myAjax = new Ajax.Request
	(
		site_address + 'ajax.php',
		{
			method: 'post',
			parameters: pars,
			onComplete: function()
			{
				Effect.toggle('media_' + media_id, 'blind');
				Effect.toggle('share_' + media_id, 'blind');
			}
		}
	)
}

function validateSearch(form, text) 
{
	if(form.search.value.length==0 || form.search.value==text) {
  		return false;
  	} else {
  		return true;
 	}
}

function changeCategory(type, category) {
	if (category) {
		window.location=site_address + type + '/?category=' + category;
	}
	else {
		window.location=site_address + type;
	}
}

function bookmark_us(address, title) {
	try {
		window.external.AddFavorite(address, title);
	}
	catch (er) {
		alert('Sorry. Not available for your browser!');
	}
	return false;
}

function homepage_us(el, address) {
	try {
		el.style.behavior='url(#default#homepage)';
		el.setHomePage(address);
	}
	catch (er) {
		alert('Sorry. Not available for your browser!');
	}
	return false;
}

function addsearch(domain, name) {
	try {
		window.external.AddSearchProvider(domain+"search/searchprovider.xml");
	}
	catch(eX) {
		if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
			window.sidebar.addSearchEngine(domain + "search/searchengine.src", domain + "favicon.ico", name, "Web");
		}
		else {
			alert("Sorry. Not available for your browser!");
		}
	}
	return false;
}

function selectAll(select)
{
	$A($$('input.checkbox')).each(function(item)
	{
		if(select == 'off')
		{
			$(item).checked = false;
		}
		else if(select == 'invert')
		{
			if ($(item).checked) {
				$(item).checked = false;
			}
			else {
				$(item).checked = true;
			}
		}
		else
		{
			$(item).checked = true;
		}
	});
}

function setFormAction(action)
{

	$('action_cage').innerHTML = '<input type="hidden" name="' + action + '" value="1" />';
	var isOK = anythingChecked($('bulkForm'));
	if(isOK == true)
	{
		$('bulkForm').submit();
	}
}


function anythingChecked (f)
{
	elms = f.elements;
	ae = false;
	ac = false;

	for (var i = 0; i < elms.length; i++)
	{
		elm = elms[i];

		if ('checkbox' == elm.type)
		{
			ae = true;

			if (true == elm.checked)
			{
				ac = true;
				break;
			}
		}
	}

	if (false == ae)
	{
		return false;
	}

	if (false == ac)
	{
		alert('Please check at least one box');
	}
	else
	{
		if (1 == deleting)
		{
			confirm('Are you sure you wish to delete?');
			deleting = 0;
		}
	}

	return ac;
}

// If we want some js to run onload, create a onloadExecute() function anywhere in the subtemplate.
function onloadCode()
{    
    if (window.onloadExecute)
    {
        onloadExecute();
    }
}

// toggle style class for an object, given an id and on/off classnames 
function toggleClass(id, onclass, offclass)
{
	var x = document.getElementById(id);
	x.className = (/onclass/.test(x.className)) ? offclass : onclass;
}

/**
*  URL encode / decode
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
