var TICKER_INTERVAL_MS = 5000; //in milli-second
var ajax_loader_content = '<div id="selLoading"><p>Loading...</p></div>';

$(document).ready(function () {
	//--------- Code begin for spy feature ----------->>>//
	$(function() {
	// In more spy page
	$('#morespy > div:gt(4)').fadeEachDown(); // initial fade
	$('#morespy').spy({'ajax': 'spy.inc.php?ajax=1', 'limit': '10', 'fadeLast ' : '4', 'fadeInSpeed': '3000', 'timeout': 10000});
    /* returns a selection of HTML DIVs to be inserted in to
        the #spyContainer in a spy-style */
	$('#holder > div:gt(4)').fadeEachDown(); // initial fade
	$('#holder').spy({'ajax': 'spy.inc.php?ajax=1', 'limit': '4', 'fadeLast ' : '2', 'fadeInSpeed': '3000', 'timeout': 10000});
  });
	//<<<------ Code end for spy feature -----------//
    $('#profile-related').tabs({ remote: true });
	$('#contest-related').tabs({ remote: true });
	$('#news-options').tabs({ fxFade: true, fxSpeed: 'fast' });
	$('#contest-options').tabs({ fxFade: true, fxSpeed: 'fast' });
    //>>>>> Coding to manage the table data sorting begins >>>>>>
    $("table.sortable").tableSorter( {
        sortClassAsc : 'sortUp', // class name for asc sorting action
        sortClassDesc : 'sortDown', // class name for desc sorting action
        headerClass : 'largeHeaders', // class name for headers (th's)
        disableHeader : ['Action', '&nbsp;', 'View']//, // disable column can be a string / number or array containing string or number.
        //dateFormat: 'yyyy/mm/dd' // set date format for non iso dates default us, in this case override and set uk-format
    });
    //<<<<< Coding to manage the table data sorting ends <<<<<
    //>>>>> Toggle of contest and sponsor links begins >>>>>
    // ajax +- to display Join Contests, Final Contests, and Finished Contests when pressed
    $('.contestsType').hide();
    $('.contestsLinks').click(function () {
        $('.contestsType', $(this)).slideToggle('slow');
    });
    //ajax +- of sponsor links
    $('.sponsorsList').hide();
    $('.sponsorsLinks').click(function () {
        $('.sponsorsList', $(this)).slideToggle('slow');
    });
    //<<<<< Toggle of contest and sponsor links ends <<<<<
    //>>>>> Toggle burried comments on clicking it's header begins >>>>>
	$('#comments .burried .content').livequery(function(){
        $('#comments .burried .content').hide();
    });
    $('#comments .burried .header').livequery('click', function(event) {
        $('.content', $(this).parent()).slideToggle('slow');
    });
    //<<<<< Toggle burried comments on clicking it's header ends >>>>>
    //>>>>> Comments ratings. Good & Bad ajax handling begins >>>>>
	$('a.clsCommentGood, a.clsCommentBad, a.clsNewsGetIt').livequery('click', function(event) {
        $(this).parent().load($(this).attr('href') + '&ajax=1');
        if ($(this).text() == 'Bad') {
            $('.content', $(this).parent().parent()).slideUp('slow');
        }
        return false;
    });
	//<<<<< Comments ratings. Good & Bad ajax handling ends <<<<<
    //>>>>> Statements rating. Ajax handling begins >>>>>
	$('a.one-star, a.two-stars, a.three-stars, a.four-stars, a.five-stars').livequery('click', function(event){
      	if ($(this).attr('href') != 'login.php')
		{
			var splited_class = $(this).attr('class').split(' ');
			$("#rate-"+splited_class[1]).text(parseInt($("#rate-"+splited_class[1]).text()) + 1);
			$(this).parent().parent().removeClass('star-rating small-star');
			$(this).parent().parent().parent().load($(this).attr('href') + '&ajax=1');
			return false;
		}
    });
    //<<<<< Statements rating. Ajax handling ends <<<<<
	//>>>>>    Ajax over display of statement using tooltip begins >>>>>
	$('span.getty-rating-avg, span.getty-power, span.prize-image').livequery(function(){
        $(this).tooltip();
    });

  //<<<<<    Ajax over display of statement using tooltip ends <<<<<

	  //-------------- To pause.play of spy content -------------->>>>///
	$('a.spy-pause').livequery('click', function() {
       return pauseSpy();
    });
	$('a.spy-play').livequery('click', function() {
       return playSpy();
    });
	//<<<<<<<-------------- To pause.play of spy content --------------///
    //>>>>> Comments ratings. Block ajax handling begins >>>>>
    $('a.clsCommentBlock').click(function () {
        $(this).parent().parent().addClass('burried');
        // for <li>
        var $_a = $(this);
        //preserve as inside $.get, $(this) vanishes
        $.get($(this).attr('href'), {
            'ajax' : 1
        }
        , function (data) {
            $_a.empty();
            $_a.parent().prepend('<span>' + data + '</span>');
        }
        );
        $('.content', $(this).parent().parent()).slideUp('slow');
        return false;
    });
    //<<<<< Comments ratings. Block ajax handling ends <<<<<
    //>>>>> Coding to handle shipping details as like the private information begins >>>>>
    $("#shipping_details_link").click(function () {
        $("#shipping_address").val($("#address").val());
        $("#shipping_city").val($("#city").val());
        $("#shipping_state").val($("#state").val());
        $("#shipping_zip").val($("#zip").val());
        $("#shipping_phone").val($("#phone").val());
        return false;
    });
    //<<<<<< Coding to handle shipping details as like the private information ends <<<<<
    //>>>>> Coding to handle countdown ends >>>>>
    $('span.count-down').each(function (c) {
        //c ===> <span class="count-down">315:09:09</span>
        $(this).attr('sec_remaining', $(this).text());
        //<span class="count-down" sec_remaining="315:09:09">315:09:09</span>
    });
    setInterval('timercountdown()', TICKER_INTERVAL_MS);
    timercountdown();
    //<<<<<< Coding to handle countdown ends <<<<<<
    //>>>>>> Coding to handle the form loading in the popup begins >>>>>
    $('.remote-load').livequery('click', function(event) {
        $this = $(this);
        //otherwise, clears the title leaving ugly look
        if ($(this).attr('title')) {
            $('.jqmdTC').text($this.attr('title'));
        } else {
            $('.jqmdTC').html('&nbsp;');
        }
        $dialogcontent = $('.dialog-content');
        $dialogcontent.html('Please wait... <img src="./images/busy.gif" alt="loading" />');
        $dialogcontent.load($this.attr('name'));

        $('#modalDialog').jqm().jqmShow().jqDrag('.jqDrag');;
        return false;
    });
    $("a.remote-nav").livequery('click', function(event) {
	    $(this).addClass("loader-bg");
	    $(this).parent().addClass("loader-bg");
		$(this).parent().parent().load($(this).attr('href')+'&ajax=1&remote_nav=1',
								null,
								function() { $(this).fadeIn('fast');}
							  );
    	return false;
    });
    // Highlights the close button of focus/hover
    $('input.jqmdClose').hover(function () {
        this.src = './images/close_hover.gif';
    }
    , function () {
        this.src = './images/close.gif';
    }
    ).focus(function () {
        this.hideFocus = true;
        this.src = './images/close_hover.gif';
    }
    ).blur(function () {
        this.src = './images/close.gif';
    });
    //<<<<<< Coding to handle the form loading in the popup ends <<<<<<<

    // for auto submit on select of filter in contests page...
    $('#form_filter tr:last').remove();
    $('form #sort, form #ufilter').change(function () {
          $('#form_filter').trigger('submit');
    }
    );

});

//>>>>>>>>>>>>>>>>>>>>>>>> Image picker code begins >>>>>>>>>>>>>>>>>>>>>>>>>>
// ----------- image picker for friends begins --------------------
function loadItemHandler1(carousel, start, last, available) {
    var sthis = this;
    if (available) {
        // Trigger loaded
        carousel.loaded();
        return;
    }
    var cr = carousel;
    if (!sthis.data) { //dirty hack to avoid multiple ajax call. Since, the ajax call returns all data, it's waste of bandwidth to request ajax
        jQuery.get($("#friends-link").attr('href') + '&ajax=1', function (data) {
            appendItemCallback1(cr, start, last, data);
            sthis.data = data;
          }
        );
    }
    else {
        appendItemCallback1(cr, start, last, sthis.data);
    }
};

// Image picker loading for friends listing
function appendItemCallback1(carousel, start, last, data) {
    var items = data.split("|");
    for (i = start; i <= last; i++) {
        if (items[i - 1] == undefined) {
            break;
        }
        var item = carousel.add(i, getItemHTML1(items[i - 1]));
    }
    // Trigger loaded
    carousel.loaded();
};
function getItemHTML1(data) {
    var split = data.split(";");
	var image_link = jQuery.trim(split[0]);
    var url = jQuery.trim(split[1]);
    var title = jQuery.trim(split[2]);
    return '<a href="' + image_link + '" title="' + title + '" class="thickbox"><img src="' + url + '" width="' + 35 + '" height="' + 35 + '" alt="' + title + '" title="' + title + '" /></a>';
};
// ----------- image picker for friends ends ---------------------
//>>>>> Image picker related function begins >>>>>>
function loadItemHandler(carousel, start, last, available) {
    var sthis = this;
    if (available) {
        // Trigger loaded
        carousel.loaded();
        return;
    }
    var cr = carousel;
    if (!sthis.data) {
        //dirty hack to avoid multiple ajax call
        jQuery.get("avatars.php?ajax=1", function (data) {
            appendItemCallback(cr, start, last, data);
            sthis.data = data;
          }
        );
    }
    else {
        appendItemCallback(cr, start, last, sthis.data);
    }
};
function appendItemCallback(carousel, start, last, data) {
    var items = data.split("|");
    for (i = start; i <= last; i++) {
        if (items[i - 1] == undefined) {
            break;
        }
        var item = carousel.add(i, getItemHTML(items[i - 1]));
        item.each(function () {
            // Urgh...ThickBox should provide a function for that
            jQuery("a.thickbox", this).bind("click", function () {
                var t = this.title || this.name || null;
                var g = this.rel || false;
                TB_show(t, this.href, g);
                this.blur();
                return false;
            }
            );
        });
    }
    // Trigger loaded
    carousel.loaded();
};
function TB_show(caption, url, imageGroup) {
    $("#new_avatar").val(caption);
    $("#current_avatar_img").attr( {
        src : url
    });
}
function getItemHTML(data) {
    var split = data.split(";");
    var url = jQuery.trim(split[0]);
    var title = jQuery.trim(split[1]);
    var url_m = url.replace(/_s.jpg/g, '_m.jpg');
    return '<a href="' + url_m + '" title="' + title + '" class="thickbox"><img src="' + url + '" width="' + 75 + '" height="' + 75 + '" alt="' + title + '" /></a>';
};
// Next-Button handling...
var nextOver = function () {
    jQuery(this).attr("src", "./images/next-over.gif");
};
var nextOut = function () {
    jQuery(this).attr("src", "./images/next.gif");
};
var nextDown = function () {
    jQuery(this).attr("src", "./images/next-down.gif");
};
function nextButtonStateHandler(carousel, button, enabling) {
    if (enabling) {
        jQuery(button).attr("src", "./images/next.gif").bind("mouseover", nextOver).bind("mouseout", nextOut).bind("mousedown", nextDown);
    }
    else {
        jQuery(button).attr("src", "./images/next-disabled.gif").unbind("unmouseover", nextOver).unbind("unmouseout", nextOut).unbind("unmousedown", nextDown);
    }
}
// Prev-Button handling
var prevOver = function () {
    jQuery(this).attr("src", "./images/prev-over.gif");
};
var prevOut = function () {
    jQuery(this).attr("src", "./images/prev.gif");
};
var prevDown = function () {
    jQuery(this).attr("src", "./images/prev-down.gif");
};
function prevButtonStateHandler(carousel, button, enabling) {
    if (enabling) {
        jQuery(button).attr("src", "./images/prev.gif").bind("mouseover", prevOver).bind("mouseout", prevOut).bind("mousedown", prevDown);
    }
    else {
        jQuery(button).attr("src", "./images/prev-disabled.gif").unbind("unmouseover", prevOver).unbind("unmouseout", prevOut).unbind("unmousedown", prevDown);
    }
}
// <<<<< Image picker related function ends <<<<
//<<<<<<<<<<<<<<<<<<<<< Imagepicker coding ends <<<<<<<<<<<<<<<<<<<<<<<<<<<<
// Ride the carousel...
jQuery(document).ready(function () {
    $('.default-avatar').hide();
    /**
    * We show a simple loading indicator
    * using the jQuery ajax events
    */
    jQuery().ajaxStart(function () {
        jQuery(".loading").show();
    });
    jQuery().ajaxStop(function () {
        jQuery(".loading").hide();
    });
    jQuery("#mycarousel").jcarousel( {
        itemVisible : 4, itemScroll : 1, wrap : false, loadItemHandler : loadItemHandler, nextButtonStateHandler : nextButtonStateHandler, prevButtonStateHandler : prevButtonStateHandler
    });
    jQuery("#mycarouse2").jcarousel( {
        itemVisible : 4, itemScroll : 1, autoScroll: 3, wrap : true, orientation : "vertical", loadItemHandler : loadItemHandler1, nextButtonStateHandler : nextButtonStateHandler, prevButtonStateHandler : prevButtonStateHandler
    });
});
function timercountdown() {
    $('span.count-down').each(function (c) {
        //<span class="count-down" sec_remaining="274845">274845</span>
        var sec_remaining = parseInt($(this).attr('sec_remaining'), 10) - (TICKER_INTERVAL_MS / 1000);
        $(this).attr('sec_remaining', sec_remaining);
        var daysDifference = 0, hoursDifference = 0, minutesDifference = 0, secondsDifference = 0;
        var date_time_to_display = 'Finished';
        if (sec_remaining > 0) {
            secondsDifference = sec_remaining % 60;
            minutesDifference = Math.floor((sec_remaining / 60) % 60);
            hoursDifference = Math.floor((sec_remaining / 3600) % 24);
            daysDifference = Math.floor((sec_remaining / (24 * 3600)));
            //show days, hours, minutes only if they're non-zero
            date_time_to_display = '';
            if (daysDifference)date_time_to_display += daysDifference + ' days ';
            if (hoursDifference || daysDifference)date_time_to_display += hoursDifference + ' hours ';
            if (minutesDifference || hoursDifference || daysDifference)date_time_to_display += minutesDifference + ' minutes ';
            date_time_to_display += secondsDifference + ' seconds';
        }
        $(this).text(date_time_to_display);
    });
}

