/*
* Copyright: 2005 - this.year() Karbonblack Creative

* This JS page controls all custom functions for the main webstie
* @page sabc2.js
* @version 1.3
* @author Greg Shiers, (Karbonblack.com)
* @copyright: Karbonblack 
*/

/*-------------------------------------------------------------------------------
 * jCustom function to show / Hide the sign up window
 * Author: Greg Shiers greg@karbonblack.com
 * Created: November 15th 2010
 * Notes: N/A
-------------------------------------------------------------------------------*/
showSignupPopup = function () {
	var su_block = $("#sign-in");
	if ( su_block.css("display")  == "none" ) {
		/**
		** We need to reset the sign in box here which means 
		** show the form
		** hide forgot pass (cause you could have activated this)
		** remove all error classes
		**/
		// Make sure forgot password his hidden
		$("#forgot-password-holder").hide();
		// And sign in is showing
		$("#sign-in-form-holder").show();
		// Make the link active (visual)
		$("#sign-in-link a").addClass("active");
		// Remove the error block if there were some
		$("#sign-in-form-holder .input-error").removeClass('input-error');
		// Fade the sign in block in, neat
		su_block.fadeIn(300);
		// Set time out and focus on element, we need to set time out cause the element is
		// Not at 100% opacity, just to make life easier for user, rrrrrap
		setTimeout(function(){
			$("#login-username").focus();
		},500);
	}
	else {
		$("#sign-in-link a").removeClass("active");
		su_block.fadeOut(300);
	}
}
/*-------------------------------------------------------------------------------
 * create a loading effect using gif and text
 * Author: Greg Shiers greg@karbonblack.com
 * Created: November 15th 2010
 * Notes: N/A
-------------------------------------------------------------------------------*/
createLoadingJobby = function ( target , message ) {
	$("#"+target).html('<div style="padding: 30px 0 0 45px;"><img src="/media/sabc2/images/ajax-loader.gif" width="16" height="16" class="icor" /><span class="white">'+message+'</span></div>');
}
/*-------------------------------------------------------------------------------
 * Custom function to fade in and out content of an innerHTML, I know it's simple
 * But we could reuse this in future
 * Author: Greg Shiers greg@karbonblack.com
 * Created: November 16th 2010
 * Notes: N/A
-------------------------------------------------------------------------------*/
swapInnerHTML = function( fadeout, fadein, time ) {
	/* set variable timer */
	var timer;
	/* if time is set in the function arguement, then we use that time, otherwise default to 300 */
	if ( time ) { timer = time; }
	else { timer = 300; }
	/* fade in and fade out relevant divs */
	$("#"+fadeout).hide(timer);
	$("#"+fadein).show(timer);
}

/*-------------------------------------------------------------------------------
 * Show more comments inside the comment block when clicking "Show More"
 * Author: Greg Shiers greg@karbonblack.com
 * Created: December 7th 2010
 * Notes: This is a temporary function to simulate the way we want it to work.
-------------------------------------------------------------------------------*/
showMoreComments = function( ) {
	$.ajax({
		type: "POST",
		/* put the URL you want to post to here, you will see the HTML we need returned */
		url: "comments-template.html",
		/* this will serialise the data */
		success: function( data ){
			/*TODO: REMOVE THIS ALERT WHEN DONE */
			$("#more-comments").html(data);
			$("#more-comments").slideDown(500, 'easeOut');
		}
	});
}

/*-------------------------------------------------------------------------------
 * Display Reply Form
 * Author: Greg Shiers greg@karbonblack.com
 * Created: December 7th 2010
 * Notes: This is a temporary function to simulate the way we want it to work.
-------------------------------------------------------------------------------*/
displayReplyComment = function( which ) {

	$.ajax({
		type: "POST",
		/* put the URL you want to post to here, you will see the HTML we need returned */
		url: "reply-template.html",
		/* this will serialise the data */
		success: function( data ){
			/* If the Ajax call is a sucssess then we perform the follow if statemet */
			/* First, we check if a reply form already exists and if it DOES NOW, we ajax to a reply form and display it, as focus to the first element */
			if ( $(which).parents('.comment-holder').find('.reply-block').length == 0 ) {
				/* Insert the data into the reply box, this should be dynamic */
				$(data).appendTo($(which).parents('.comment-holder'));
				$(which).parents('.comment-holder').find('.reply-block input')[0].focus();
			}
			/* If there reply for already exists, we must not load another one, simply focus to the first input */
			else {
				$(which).parents('.comment-holder').find('.reply-block input')[0].select();
			}
		}
	});
}

/*-------------------------------------------------------------------------------
 * Here is where we set up the slider
 * Author: Greg Shiers greg@karbonblack.com
 * Created: November 16th 2010
 * Notes: N/A
-------------------------------------------------------------------------------*/
var theInt = null;
var $crosslink, $navthumb;
var curclicked = 0;

theInterval = function(cur){
	clearInterval(theInt);
	
	if( typeof cur != 'undefined' )
		curclicked = cur;
	
	$crosslink.removeClass("active-thumb");
	$navthumb.eq(curclicked).parent().addClass("active-thumb");
		$(".stripNav ul li a").eq(curclicked).trigger('click');
	
	theInt = setInterval(function(){
		$crosslink.removeClass("active-thumb");
		$navthumb.eq(curclicked).parent().addClass("active-thumb");
		$(".stripNav ul li a").eq(curclicked).trigger('click');
		curclicked++;
		if( 6 == curclicked )
			curclicked = 0;
		
	}, 8000);
};

$(function(){
    $("#main-photo-slider").css("display", "inline");
	$("#main-photo-slider").codaSlider();
	
	$navthumb = $(".nav-thumb");
	$crosslink = $(".cross-link");
	
	$navthumb.click(function() {
		var $this = $(this);
		theInterval($this.parent().attr('href').slice(1) - 1);
		return false;
	});
	theInterval();
});

/*-------------------------------------------------------------------------------
 * Setting up jCarousel's main functions and methods
 * Author: SABC Developer
 * Created: November 16th 2010
 * Notes: Adapted and commented from SABC3 codebase
-------------------------------------------------------------------------------*/
function showcarousel_itemFirstInCallback(carousel, item, idx, state) {
	/* Create an array of days of the week to corrolate with their index, remember it starts at 0 */
    var days = new Array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
    /* Check if the days array matched the day today and convert the text to "Today" */
	days[parseInt($("#show_carousel").attr("today_weekday"))] = "Today";
    var current_weekday = parseInt($("#show_carousel").attr("current_weekday"));
    var entry_days_index = parseInt($(item).attr('entry_day'));
	/* Check first if the entry day is not the same as current weekday */
	if (entry_days_index != current_weekday) {
		/* load entry day into assigned variable */
        var entry_day = days[entry_days_index];
        $("#bc-carousel-nav .bc-caoursel-nav-item:first").text(entry_day + " on SABC 2");
        /* remove all "on" classes on href array */
		$("#bc-caoursel-week-days").find("a").removeClass("on");
		/* add "on" active class to correct href */
        $($("#bc-caoursel-week-days").find("a")[entry_days_index]).addClass("on");
        $("#show_carousel").attr("current_weekday", entry_days_index);
    }
};

/*-------------------------------------------------------------------------------
 * Deprciated function
 * Author: SABC Developer
 * Created: November 16th 2010
 * Notes: NULL Function
-------------------------------------------------------------------------------*/
function showcarousel_itemVisibleInCallbackBeforeAnimation(carousel, item, idx, state) {
    //var img = $(item).find("img");
    //img.attr("src", img.attr("href"));
};

/*-------------------------------------------------------------------------------
 * Show the callback and add onair entry PNG to currently showing show.
 * Author: SABC Developer
 * Created: November 16th 2010
 * Notes: Adapted and commented from SABC3 codebase
-------------------------------------------------------------------------------*/
function showcarousel_initCallback(carousel) {

    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
    
    $("#bc-caoursel-week-days a").each(function(i) {
        var elem = $(this);
        elem.click(function() {
            carousel.scroll($.jcarousel.intval(elem.attr("entry_start")));
        });
    });
};

$(function(){
    var on_air_entry_index = $("#show_carousel").attr("on_air_entry_index");
    var start_index = parseInt(on_air_entry_index) - 1;
    if (start_index < 0) {
        start_index = 0;
    }
    $("#show_carousel").css("display", "block");

    $("#show_carousel ul").jcarousel({ 
            scroll: 1,
            auto: 6,
            wrap: 'last',
            start: start_index,
            initCallback: showcarousel_initCallback,
            itemFirstInCallback: {
                onBeforeAnimation: showcarousel_itemFirstInCallback
            },
            itemVisibleInCallback: {
                onBeforeAnimation: showcarousel_itemVisibleInCallbackBeforeAnimation
            }
    });
});

/**
 * --------------------------------------------------------------------
 * jQuery-Plugin "pngFix"
 * Version: 1.1, 11.09.2007
 * by Andreas Eberhard, andreas.eberhard@gmail.com
 * http://jquery.andreaseberhard.de/
 *
 * Copyright (c) 2007 Andreas Eberhard
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*/
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([237-9n-zA-Z]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(s(m){3.fn.pngFix=s(c){c=3.extend({P:\'blank.gif\'},c);8 e=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 5.5")!=-1);8 f=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 6.0")!=-1);p(3.browser.msie&&(e||f)){3(2).B("img[n$=.C]").D(s(){3(2).7(\'q\',3(2).q());3(2).7(\'r\',3(2).r());8 a=\'\';8 b=\'\';8 g=(3(2).7(\'E\'))?\'E="\'+3(2).7(\'E\')+\'" \':\'\';8 h=(3(2).7(\'F\'))?\'F="\'+3(2).7(\'F\')+\'" \':\'\';8 i=(3(2).7(\'G\'))?\'G="\'+3(2).7(\'G\')+\'" \':\'\';8 j=(3(2).7(\'H\'))?\'H="\'+3(2).7(\'H\')+\'" \':\'\';8 k=(3(2).7(\'V\'))?\'float:\'+3(2).7(\'V\')+\';\':\'\';8 d=(3(2).parent().7(\'href\'))?\'cursor:hand;\':\'\';p(2.9.v){a+=\'v:\'+2.9.v+\';\';2.9.v=\'\'}p(2.9.w){a+=\'w:\'+2.9.w+\';\';2.9.w=\'\'}p(2.9.x){a+=\'x:\'+2.9.x+\';\';2.9.x=\'\'}8 l=(2.9.cssText);b+=\'<y \'+g+h+i+j;b+=\'9="W:X;white-space:pre-line;Y:Z-10;I:transparent;\'+k+d;b+=\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;\';b+=\'J:K:L.t.M(n=\\\'\'+3(2).7(\'n\')+\'\\\', N=\\\'O\\\');\';b+=l+\'"></y>\';p(a!=\'\'){b=\'<y 9="W:X;Y:Z-10;\'+a+d+\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;">\'+b+\'</y>\'}3(2).hide();3(2).after(b)});3(2).B("*").D(s(){8 a=3(2).11(\'I-12\');p(a.A(".C")!=-1){8 b=a.13(\'url("\')[1].13(\'")\')[0];3(2).11(\'I-12\',\'none\');3(2).14(0).15.J="K:L.t.M(n=\'"+b+"\',N=\'O\')"}});3(2).B("input[n$=.C]").D(s(){8 a=3(2).7(\'n\');3(2).14(0).15.J=\'K:L.t.M(n=\\\'\'+a+\'\\\', N=\\\'O\\\');\';3(2).7(\'n\',c.P)})}return 3}})(3);',[],68,'||this|jQuery||||attr|var|style||||||||||||||src|navigator|if|width|height|function|Microsoft|appVersion|border|padding|margin|span|px|indexOf|find|png|each|id|class|title|alt|background|filter|progid|DXImageTransform|AlphaImageLoader|sizingMethod|scale|blankgif|appName|Internet|Explorer|parseInt|MSIE|align|position|relative|display|inline|block|css|image|split|get|runtimeStyle'.split('|'),0,{}));

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);
$(document).ready(function(){
	/* Load the PNG fix class through the above pack */
	$(document).pngFix();
	/* run script to preload CSS images **/
	// $.preloadCssImages();
	/* load ez checkbox */
	$('input[type="checkbox"]').ezMark();
	/* Turn off all the autocompletes for input fields */
	$('input[type=text]').attr("autocomplete","off");

	/* * * * * * * * * * * * LOAD ALL CLICK / LINK EVENTS* * * * * * * * * * * * * * * * * */

	/* Trigger a click event on the sign in button which makes the popup appear */
	$("#sign-in-link a").click(function(event){
		showSignupPopup();
		event.preventDefault(event);
	});
	/* Show the forgot password content, and hide the sign in content */
	$("#forgot-link").click(function(event){
		event.preventDefault(event);
		swapInnerHTML('sign-in-form-holder','forgot-password-holder',200);
	});
	/* Show the signin content, and hide the forgot password content */
	$("#sign-in-link-swap").click(function(event){
		event.preventDefault(event);
		swapInnerHTML('forgot-password-holder','sign-in-form-holder',200);
	});
	/* Show more comments */
	$("#show-more").click(function(event){
		event.preventDefault(event);
		showMoreComments();
	});

	$(".reply").bind('click', function( event ) {
		event.preventDefault();
		displayReplyComment(this);
	});

	/* Load the hover menu for shows using jQuery hoverIntent plugin */
	function addMega(){ $(this).addClass("hoveractive"); }
	function removeMega(){ $(this).removeClass("hoveractive"); }
	var megaConfig = {
		interval: 0,
		sensitivity: 1,
		over: addMega,
		timeout: 0,
		out: removeMega
	};
	$("#navigation ul li:first").hoverIntent(megaConfig)
	 
})

