var uc = uc || {};
uc.common = uc.common || {};

//Ajaxify content
uc.common.ajaxify = function (timeout) {
	if (timeout == null) timeout = 0;
	
	// Fix section header width
	// Wait a time to make sure css is loaded
	window.setTimeout(uc.common.fixSectionStyle, timeout);
	
	uc.utils.ajaxifyLink(jQuery('a.ajax-post'), 'POST', function() {uc.common.ajaxify();});
	uc.utils.ajaxifyLink(jQuery('a.ajax'), 'GET', function() {uc.common.ajaxify();});
	uc.utils.ajaxifyLink(jQuery('.ajax a'), 'GET', function() {uc.common.ajaxify();});
	uc.utils.ajaxifyForm(jQuery('form.ajax'), function() {uc.common.ajaxify();});
}

uc.common.fixSectionStyle = function() {
	jQuery('.border-section').each(function(index) {
		var jq_section = jQuery(this);
		var section_width = jq_section.outerWidth();
		var jq_head = jQuery('.head', jq_section);
		var head_width = jq_head.outerWidth();
		var jq_header = jQuery('.section-header', jq_section);
		var header_padding = parseInt(jq_header.css('padding-left')) + parseInt(jq_header.css('padding-right')) + 2;
		jq_header.width(section_width-head_width-header_padding);
	});
}

// Process document after its loading
jQuery(document).ready(function() {
	// Cycle
	uc.cycle.build("ul.cycle-list");
	
	// Ajaxify
	uc.common.ajaxify(200);
	
	// Add help feature to input text
	jQuery('input.help[type=text]').each(function(index) {
		var jq_this = jQuery(this);
		var help = jq_this.val();
		jq_this.focus(function() {if (jq_this.val() == help) jq_this.val('');});
		jq_this.blur(function() {if (jq_this.val() == '') jq_this.val(help);});
	});

	// Wrap select list. If user click on a list item, add a 'selected' class
	uc.utils.buildSelectList(jQuery('ul.select-list'));
	
	// Add livesearch on search input
	uc.search.build('#search input', 2, '#page', 316, -11);

	// Form rating
	uc.rating.build('form select.input-rating', 10);

	jQuery('.form-rating').bind('rated', function () {
		jQuery(this).submit();
	});

	// Add scrolling wrapper around image playlist
	jQuery('.image-playlist').each(function() {
		jq_this = jQuery(this);

		if (jQuery('ul.media-list li', this).length > 4) {
			jQuery('.scrolling', jq_this).scrollable({items: 'ul', size: 4, clickable: false, prevPage: '.rewind-page', nextPage: '.forward-page'});
		} else {
			jQuery('.rewind-page, .forward-page', jq_this).addClass('disabled');
		}

	});

	// Instantiate all flow player
	uc.player.build(".media-playlist");
	
	jQuery('a.cycle-random-list').each(function () {
		var jq_this = jQuery(this);
		var json_url = jq_this.attr('href');
		jQuery.ajax({
			url: json_url,
			beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "application/json");},
			complete: function (XMLHttpRequest, textStatus) {},
			success: function (data, textStatus) {alert(data);},
			dataType: "script"
		})
	});	
});

