/**
 * (c) Copyright 2008-2009 Arkena A/S
 * daniel@arkena.com
 */

Shadowbox.loadSkin('classic_mod',	'http://'+resource_site_hostname+'/js/shared/shadowbox/skin');
Shadowbox.loadLanguage('mute',		'http://'+resource_site_hostname+'/js/shared/shadowbox/lang');
Shadowbox.loadPlayer(['html'],		'http://'+resource_site_hostname+'/js/shared/shadowbox/player');

var shadowbox_tmp = [];

// Setup the page once the document is ready:
$(document).ready
(
	function()
	{
			Shadowbox.init({
				showMovieControls:	false,
				displayNav:			false,
				enableKeys:			false,
				animate:			false,
				resizeDuration:		0.15, // We've hidden the loading box via CSS, and we've said animate:false, so this really has no effect.
				fadeDuration:		0.25,
				onFinish:			function(element) { // Hide the shadowbox frame after the content has been loaded
					shadowbox_tmp['border']				= $('#shadowbox_body').css('border');
					shadowbox_tmp['top']				= $('#shadowbox_body').css('top');
					shadowbox_tmp['left']				= $('#shadowbox_body').css('left');
					shadowbox_tmp['background-color']	= $('#shadowbox_body').css('background-color');
			},
				onClose:			function(element) { // Restore the shadowbox frame on close
				$('#shadowbox_body').css('border', shadowbox_tmp['border']);
				$('#shadowbox_body').css('top', shadowbox_tmp['top']);
				$('#shadowbox_body').css('left', shadowbox_tmp['left']);
				$('#shadowbox_body').css('background-color', shadowbox_tmp['background-color']);
			},
				handleException:	function(e) { /*alert('shadowbox exception caught');*/ }
			});
			fix_ie6_pngs();

//	    $.initCursorSpinner({image_src: '/images/cursor_spinner.png'});
	}
);





/**
 * Will turn a regular form into an AJAX form.
 * Version: 20080909.14.30
 * daniel@arkena.dk
 *
 * @param {Object} params Parameters as member variables:
 * 	{object}	.target_element
 * 					The actual DOM form element to process.
 * 		OR
 * 	{string}	.target_id
 * 					The DOM id of the form to process.
 *  {string}	.submit_url
 * 					Where to submit to. If omitted, the value of the form's "action" attribute will be used.
 * 	{function}	.submit_callback
 * 					A function to call after the form has been submitted, with the server response object passed on.
 *  {function}	.cancel_callback
 * 					A function to call when the user clicks button(s) of type "reset" in the form. (Optional)
 *  {boolean}	.track_input_states
 * 					Use this if you plan on changing input field values, e.g. to report back input errors to the user.
 * 					The value, style, and class of each input field will be tracked and restored on focus to the field.
 * 					Applies to <input>s and <textarea>s.
 *  {boolean}	.clear_texts_on_first_focus
 * 					If true, input fields will have their values cleared when they're first focused.
 * 					Applies to <input>s and <textarea>s.
 * 	{boolean}	.use_mouse_spinner
 * 					Attaches a mouse spinner while waiting for AJAX calls. REQUIRES jquery_cursor_spinner.js plugin.
 */
function ajaxifyForm(params)
{
	var form						= is_defined(params.target_element) ? $(params.target_element) : $('#' + params.target_id);
	var submit_url					= is_defined(params.submit_url) ? params.submit_url : $(form).attr('action');
	var submit_buttons				= form.find(":submit");
	var cancel_buttons				= form.find(":reset") ? form.find(":reset")[0] : null;
	var track_input_states			= params.track_input_states == true;
	var clear_texts_on_first_focus	= params.clear_texts_on_first_focus == true;
	var use_mouse_spinner			= params.use_mouse_spinner == true;

	// IE6 (and possibly other retarded browsers) go weirdo with
	// AJAX'ed forms and the return key. To avoid them submitting
	// regularly (i.e. sending the user to a new page with JSON
	// data printed out in all its glory) when the enter key is
	// pressed, we simply add onsubmit="return false;" to the form:
	form.submit(function() { return false; });

	// To be able to do several things on the same event, we build an
	// array of functions to fire on each event. Then, finally we let
	// the event triggers traverse their respective function arrays to
	// fire any and all events on demand. Neat :)
	if (track_input_states || clear_texts_on_first_focus)
	{
		var functions_focus = [], functions_change = [];

		// This one to make sure (IE) that the caret isn't placed
		// at the beginning of the text in an input field after
		// doing manipulation of the text via one of our functions.
		place_caret_at_text_end = function(element)
		{
			if (element.setSelectionRange) /* DOM */
			{
				setTimeout( /* hack for select delay */
					function(t)
					{
						t.setSelectionRange(t.value.length,t.value.length);
					}
					,0,element
				);
			}
			else if (element.createTextRange) /* IE */
			{
				r=element.createTextRange();
				r.collapse(false);
				r.select();
			}
		}

		if (clear_texts_on_first_focus)
		{
			clear_text_on_first_focus = function(element)
			{
				var me = $(element);
				if (me.attr('text_cleared_on_first_focus') != 'yes')
				{
					me.attr('text_cleared_on_first_focus', 'yes');
					me.val('');
				}
			}
			functions_focus.push(clear_text_on_first_focus);
		}

		if (track_input_states)
		{
			store_input_state = function(element)
			{
				var me = $(element);
				// We only store input states when we're in our original state or hasn't had our state stored yet:
				if (!is_defined(me.attr('initial_style')) || (me.attr('initial_style') == me.attr('style') && me.attr('initial_class') == me.attr('class')))
				{
					// If text clearing on first focus is on, we need to
					// make sure we're not tracking the value to be cleared:
					me.attr('cached_val',		(clear_texts_on_first_focus && me.attr('text_cleared_on_first_focus') != 'yes') ? '' : me.val());
					me.attr('initial_style',	me.attr('style'));
					me.attr('initial_class',	me.attr('class'));
				}
			}
			restore_input_state = function(element)
			{
				var me = $(element);
				// We only restore input states when we're not in our original state and have had our state stored already:
				if (me.attr('initial_style') != me.attr('style') || me.attr('initial_class') != me.attr('class'))
				{
					me.val(me.attr('cached_val'));
					me.attr('style', me.attr('initial_style'));
					me.attr('class', me.attr('initial_class'));
				}
			}
			functions_focus.push(restore_input_state);
			functions_change.push(store_input_state);
			form.find('input[type="text"], textarea').each(function(event) { store_input_state(this); });
		}
		form.find('input[type="text"], textarea').focus(function(event)	{ for(i=0; i<functions_focus.length; ++i)	functions_focus[i]((this)); place_caret_at_text_end(this); });
		form.find('input[type="text"], textarea').change(function(event)	{ for(i=0; i<functions_change.length; ++i)	functions_change[i]((this)); });
	}

	var submitFunction = function()
	{
		// We don't submit if any of our fields are in a non-initial state (with regards to
		// style & class), which is synonymous to erroneous.
		if (track_input_states)
		{
			var okay_to_submit = true;
			form.find('input[type="text"], textarea').each(function(event) { me = $(this); if (me.attr('initial_style') != me.attr('style') || me.attr('initial_class') != me.attr('class')) okay_to_submit = false; });
			if (!okay_to_submit) return false;
		}

		// Store all input states on the form's text areas if we're tracking states. We don't
		// have to do any extra checks now, since we're borking out above, if any input field
		// is in an erroneous state:
		if (track_input_states) form.find('input[type="text"], textarea').each(function() { store_input_state(this); this.blur(); });

		if (use_mouse_spinner)
			$.attachCursorSpinner();

		// Collect post data (select every element with a name attribute in the form):
		var post_data = {};
		$('*[name]', form).each(function() {
			var element = $(this);
			post_data[element.attr('name')] = (element.attr('type') == 'checkbox') ? ((element.attr('checked') == true) ? 1 : 0) : element.val();
		});

		// In case there's more than one submit button, we need to make sure we include the right value:
		if (!is_empty($(this).attr('name'))) post_data[$(this).attr('name')] = $(this).val();

		// Post:
		$.post(submit_url,
			post_data,
			function(response)
			{
				if (use_mouse_spinner)
					$.removeCursorSpinner();

				if (is_defined(params.submit_callback)) params.submit_callback(response);
			},
			'json'
		);
	}

	// Override the regular submit behavior on the submit buttons:
	$(submit_buttons).click(submitFunction);

	// Configure the cancel button, if requested:
	if (is_defined(params.cancel_callback)) $(cancel_buttons).click(params.cancel_callback);
}




/**
 * Small thingamijig to make sure any and all hrefs within a given
 * dom object open in new windows.
 */
var links_to_new_windows = function(dom_id) {
	$('#'+dom_id).find('a').each(function() { $(this).attr('target', '_blank'); });
}




function subscriptionSubmitCallback(response)
{
	// If there are errors on specific fields, we notify the user by turning those fields red and writing a notification inside the fields.
	if (!response.success && is_defined(response.erroneous_fields))
	{
		// Change the state of bad input field to erroneous:
		$.each(response.erroneous_fields, function(field_name, message) {
			$(':input[name="'+field_name+'"]').val(message).removeClass('subscribeInput').addClass('subscribeInputError');
		});
	}
	else
	{
		// Clear any checkboxes if specified:
		if (is_defined(response.clearable_checkboxes))
			for (i=0; i<response.clearable_checkboxes.length; ++i) {
				$('#'+response.clearable_checkboxes[i]).removeAttr('checked');
			};

		// If there's a message, we pop it:
		if (!is_empty(response.message))
			alert(response.message);

		// If there's html we shadowbox it:
		if (!is_empty(response.html))
			Shadowbox.open({player:'html', content:response.html, width:680, height:200+(response.subscriptions_count*40)});
	}
}

var commentsHidden = true;
function showHideComments(linkObj, isLive, clipId, commentsString, descriptionString)
{
	if( commentsHidden == true )
	{
		commentsHidden = false;
		linkObj.className = 'CS_description';
		linkObj.innerHTML = descriptionString;
		$('#clipDataWrapper').load('/res/xhr_video_player_comments.php?live='+isLive+'&clip='+clipId);
	}
	else
	{
		commentsHidden = true;
		linkObj.className = 'CS_comments';
		linkObj.innerHTML = commentsString;
		$('#clipDataWrapper').load('/res/xhr_video_player_info.php?live='+isLive+'&clip='+clipId);
	}
}


function clipCommentSubmitCallback(response, clip_id)
{
	if (response.success)
	{
		$('#clipDataWrapper').load('/res/xhr_video_player_comments.php?clip='+clip_id+'&please_stop_caching_me='+(new Date).getTime());
	}
	else
	{
		alert(response.message);
	}
}



function showGuidelinesBox()
{
	// Load the guidelines box contents:
	$.get('/res/xhr_shadowbox_guidelines.php', {}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:360})
		return false;
	});
}




function showContactBox()
{
	// Load the contact box contents:
	$.get('/res/xhr_shadowbox_contact.php', {}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:560})
		return false;
	});
}




function showDisclaimerAndDisclosureBox()
{
	// Load the guidelines box contents:
	$.get('/res/xhr_shadowbox_disclaimer_and_disclosure.php', {}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:760})
		return false;
	});
}




function showFlashHelpBox()
{
	// Load the flash helper box contents:
	$.get('/res/xhr_shadowbox_flash_help.php', {}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:450})
		return false;
	});
}




function showPodcastBox(params)
{
	// Load the podcast box contents:
	$.get('/res/xhr_shadowbox_podcast.php', {id:params.clip_id}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:550});
		return false;
	});
}


function showFlashShareBox(params)
{
	// Load the contact box contents:
	$.get('/res/xhr_shadowbox_social_share.php', {key:params}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:560})
		return false;
	});
}

function showShareBox(params)
{
	// Load the contact box contents:
	$.get('/res/xhr_shadowbox_social_share.php', {id:params.clip_id}, function(data){
		// Shadowbox it:
		Shadowbox.open({player:'html', content:data, width:680, height:560})
		return false;
	});
}


/**
 * Workaround for the Flash player which seemingly can't call
 * something with a JSON object? This one just takes the clip
 * key string and wraps it for the regular function.
 */
function showFlashFriendNotifierBox(clip_key)
{
	showFriendNotifierBox({clip_key:clip_key});
}




function showFriendNotifierBox(params)
{
	// Load the podcast box contents:
	$.get('/res/xhr_shadowbox_friend_notifier.php', {key:params.clip_key.substring(0, 15)}, function(data){
		// Shadowbox it (IE6 needs a bit more height, or it'll show scrollbars):
		Shadowbox.open({player:'html', content:data, width:680, height:400});
		// Ajaxify the form. We need to do this after the box has loaded, since the form elements are not present in
		// the DOM yet, they're still in the data variable. Only after Shadowbox has loaded and inserted the data
		// will it be present. We apply the new onFinish function to Shadowbox's options (for some reason we gotta do
		// this _after_ we've called .open() or it won't work):
		Shadowbox.applyOptions({
			onFinish:function() {
				// Ajaxify:
				ajaxifyForm({target_id:'friend_notification_form', clear_texts_on_first_focus:true, track_input_states:true, submit_callback:notifyFriendSubmitCallback});
				// Revert to the previous options:
				Shadowbox.revertOptions();
				// We're really extending, not overriding, so we need to trigger the previous onFinish method:
				Shadowbox.getOptions().onFinish();
			}
		});
		// Don't follow links:
		return false;
	});
}




function notifyFriendSubmitCallback(response)
{
	// If there are errors on specific fields, we notify the user by turning those fields red and writing a notification inside the fields.
	if (!response.success && is_defined(response.erroneous_fields))
	{
		// Change the state of each input field to erronous:
		$.each(response.erroneous_fields, function(field_name, message) {
			$('#friend_notification_form').find('#'+field_name+'.tipInput').val(message).removeClass('tipInput').addClass('tipInputError');
		});
	}
	else
	{
		respondToUser(response);
		if (response.success) Shadowbox.close();
	}
}




function respondToUser(response)
{
	if (!is_empty(response.message)) alert(response.message);
}




function restore_clip_rating(rating)
{
	for (i=1; i<6; ++i)
	{
		$('#rate'+i).attr('src', ('/images/star_' + ((i<=rating)?'on':'off') + '.gif'));
	}
}




function mouse_over_rating(rating)
{
	for (i=1; i<=rating; ++i)
	{
		$('#rate'+i).attr('src', '/images/star_over.gif');
	}
}



function notify_user(args)
{
	alert(args.message);
}



function rate_clip(args)
{
	$.attachCursorSpinner();

	// Post:
	$.post('/res/xhr_rate_clip.php',
		{clip_id:args.clip_id, rating:args.rating},
		function(response)
		{
			$.removeCursorSpinner();

			// If successful and the avg rating was changed, we update ratings and the mouseover call on the stars:
			if (response.success && is_defined(response.updated_rating))
			{
				for (i=1; i<6; ++i)
				{
					$('#rate'+i).mouseout(function() { restore_clip_rating(response.updated_rating);});
				}
				restore_clip_rating(response.updated_rating);
			}
			notify_user(response);

		},
		'json'
	);
}




/**
 * Expands a collapsable box, and saves the state in a user cookie.
 *
 * Pre: The DOM id of the container div must be the
 *      same as <args.target_id> + '_container'
 *
 * @args.target_id string The dom id of the header of the box to expand.
 * @args.content_url string The URL of the content resource to load into the box.
 *
 */
function expandCollapsableBox(args)
{
	var target_box		= $('#'+args.target_id);
	var target_box_list	= $('#'+args.target_id+'_container');
	// If the content is loaded, we simply switch classes.
	if (!is_defined(args.content_url) || target_box.attr('state_of_presence') == 'loaded')
	{
		target_box.removeClass('rightMenu_collapsed').addClass('rightMenu_expanded');
		target_box_list.removeClass('rightMenuContent_hidden').addClass('rightMenuContent_show');
		$.cookie('jb_webtv_' + args.target_id + '_expanded', 'yes', {expires:90, path:'/', domain:'.jyskebank.tv'});
		if (is_defined(args.tooltip_expanded)) $('#' + args.target_id).attr('title', args.tooltip_expanded);
	}
	else // If not, we have to load the content first:
	{
		// Show a spinner by the cursor:
		$.attachCursorSpinner();
		// Load the content:
		target_box_list.load(args.content_url, function() {
			target_box.attr('state_of_presence', 'loaded');
			fix_ie6_pngs();
			expandCollapsableBox(args);
			$.removeCursorSpinner();
			if (is_defined(args.tooltip_expanded)) $('#' + args.target_id).attr('title', args.tooltip_expanded);
		});
	}
}


/**
 * Collapses a collapsable box, and saves the state in a user cookie.
 *
 * Pre: The DOM id of the container div must be the
 *      same as <args.target_id> + '_container'
 *
 * @args.target_id string The dom id of the header of the box to collapse.
 */
function collapseCollapsableBox(args)
{
	$('#' + args.target_id).removeClass('rightMenu_expanded').addClass('rightMenu_collapsed');
	$('#' + args.target_id + '_container').removeClass('rightMenuContent_show').addClass('rightMenuContent_hidden');
	$.cookie('jb_webtv_' + args.target_id + '_expanded', 'no', {expires:90, path:'/', domain:'.jyskebank.tv'});
	if (is_defined(args.tooltip_collapsed)) $('#' + args.target_id).attr('title', args.tooltip_collapsed);
}



/**
 * Expands a collapsed box, collapses an expanded box.
 *
 * Pre: The DOM id of the container div must be the
 *      same as <target_id> + '_container'
 *
 * @args {Object} args Parameters as member variables:
 * 	.target_id string The DOM id of the box header div.
 */
function toggleCollapsableBox(args)
{
	if ($('#' + args.target_id).is('.rightMenu_collapsed'))
	{
		expandCollapsableBox(args);
	}
	else
	{
		collapseCollapsableBox(args);
	}
}


/**
 * Restores the state of a collapsable box from user's cookie,
 * if state there is set. Otherwise sets to default value.
 *
 * Pre: The DOM id of the container div must be the
 *      same as <header div> + '_container'
 *
 * @args {Object} args Parameters as member variables:
 * 	.target_id string The DOM id of the box header div.
 * 	.default_expanded bool Whether, if no state has been recorded in the user's cookie, to show as expanded.
 */
function restoreCollapsableBoxState(args)
{
	var cookie_value = $.cookie('jb_webtv_' + args.target_id + '_expanded');
	if (cookie_value == 'yes' || (cookie_value == null && args.default_expanded))
	{
		expandCollapsableBox(args);
	}
	else
	{
		collapseCollapsableBox(args);
	}
}


/**
 *  Update statistics counter in database when user clicks
 *  a social networking link.
 *
 *  @args
 *  clip_id  int     The Clip. Coming soon to a theater near you.
 *  service  string  Social network service this clip is send to
 */
function updateStat(service, ip, clipid)
{
	$.ajax({
		type: "POST",
		data: "share=1&service=" + service + "&ip=" + ip + "&clipid=" + clipid,
		url:  "/res/xhr_shadowbox_social_share.php" });
}


/**
 *  Login procedure for sharing a link on a Wordpress blog
 *  - reveal input field for URL to WP installation
 *  - open the URL in an iFrame (?)
 *  - user log in to the blog
 *  - finish by posting the clip
 *
 *  @args
 *  clip_url    string  URL for clip
 *  clip_title  string  Clip title
 *  clip_teaser string  Clip description or teaser text
 */
function wordpressWindow(clip_url, clip_title, clip_teaser)
{
	var blog_url = document.getElementById('blog_url').value;
	// http://<URL>/wp-login.php?action=auth&redirect_to=http://<URL>/wp-admin/press-this.php?u=<CLIP_URL>&t=<CLIP_TITLE>
	var url      = "http://" + blog_url +  "/wp-admin/press-this.php?u=" + clip_url + "&t=" + encodeURIComponent(clip_title) + "&s=" + encodeURIComponent(clip_teaser);

	window.open(url, '', 'scrollbars=no,menubar=no,height=470,width=720,resizable=yes,toolbar=no,location=no,status=no');
}

function popupWindow(url, h, w)
{
	window.open(url, '', 'scrollbars=no,menubar=no,height='+ h +',width=' + w + ',resizable=yes,toolbar=no,location=no,status=no');
}