var oCache = {
	iCacheLower: -1
};

function fnSetKey( aoData, sKey, mValue )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			aoData[i].value = mValue;
		}
	}
}

function fnGetKey( aoData, sKey )
{
	for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
	{
		if ( aoData[i].name == sKey )
		{
			return aoData[i].value;
		}
	}
	return null;
}

function fnDataTablesPipeline ( sSource, aoData, fnCallback ) {
	var iPipe = 5; /* Ajust the pipe size */
	
	var bNeedServer = false;
	var sEcho = fnGetKey(aoData, "sEcho");
	var iRequestStart = fnGetKey(aoData, "iDisplayStart");
	var iRequestLength = fnGetKey(aoData, "iDisplayLength");
	var iRequestEnd = iRequestStart + iRequestLength;
	oCache.iDisplayStart = iRequestStart;
	
	/* outside pipeline? */
	if ( oCache.iCacheLower < 0 || iRequestStart < oCache.iCacheLower || iRequestEnd > oCache.iCacheUpper )
	{
		bNeedServer = true;
	}
	
	/* sorting etc changed? */
	if ( oCache.lastRequest && !bNeedServer )
	{
		for( var i=0, iLen=aoData.length ; i<iLen ; i++ )
		{
			if ( aoData[i].name != "iDisplayStart" && aoData[i].name != "iDisplayLength" && aoData[i].name != "sEcho" )
			{
				if ( aoData[i].value != oCache.lastRequest[i].value )
				{
					bNeedServer = true;
					break;
				}
			}
		}
	}
	
	/* Store the request for checking next time around */
	oCache.lastRequest = aoData.slice();

	if ( bNeedServer )
	{
		if ( iRequestStart < oCache.iCacheLower )
		{
			iRequestStart = iRequestStart - (iRequestLength*(iPipe-1));
			if ( iRequestStart < 0 )
			{
				iRequestStart = 0;
			}
		}
		
		oCache.iCacheLower = iRequestStart;
		oCache.iCacheUpper = iRequestStart + (iRequestLength * iPipe);
		oCache.iDisplayLength = fnGetKey( aoData, "iDisplayLength" );
		fnSetKey( aoData, "iDisplayStart", iRequestStart );
		fnSetKey( aoData, "iDisplayLength", iRequestLength*iPipe );
		$('#pleaseWait').show();
		$.getJSON( sSource, aoData, function (json) { 
			/* Callback processing */
			oCache.lastJson = jQuery.extend(true, {}, json);
			
			if ( oCache.iCacheLower != oCache.iDisplayStart )
			{
				json.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
			}
			json.aaData.splice( oCache.iDisplayLength, json.aaData.length );
			fnCallback(json);
		} );
	}
	else
	{
		json = jQuery.extend(true, {}, oCache.lastJson);

		json.sEcho = sEcho; /* Update the echo for each response */
		json.aaData.splice( 0, iRequestStart-oCache.iCacheLower );
		json.aaData.splice( iRequestLength, json.aaData.length );
		fnCallback(json);
		return;
	}
}

function fixupBrokenAnchors() {
    $('a[href=#]').attr('href','#sfa'); // sfa stands for scroll fighter anchor!
}
    
function moveScrollingAnchor() {
    var currentScrollTop = $(document).scrollTop();
    $('#sfa').css({'top':currentScrollTop});
}

function bindQuestionText() {
    $('.questionText').bind('click', {}, function() {
	    var questionOwnerId = $(this).attr('questionOwnerId');
	    if (questionOwnerId != undefined) {
		var target = '/question/qo/' + questionOwnerId;
	    } else {
		var questionId = $(this).attr('questionId');
		var target = '/question/q/' + questionId;
	    }
	    document.location = target;
	});
}


function sortAllQuestions() {
    if ($('#allQuestionsTable').length == 1) {
	var allQuestionsTable = $('#allQuestionsTable').dataTable( {
	    "bFilter" : true, // this must be true or else when user resorts, the filtering will get lost
	    "iDisplayLength" : 10,
	    "oLanguage" : {
		"sInfo" : "_START_-_END_ of _TOTAL_ questions" },
	    "bLengthChange" : false,
	    "bPaginate" : true,
	    "bStateSave" : true,
	    "sPaginationType" : "full_numbers",
	    "fnDrawCallback": function() {
			$('#pleaseWait').hide();
			$('#allQuestionsTable').css({marginTop:'0px'});
			//$('.questionText, .numAnswers').bt({width: 300}); // bind the lullabot tooltip	
			bindQuestionText();
			var allQuestionsTable = getGlobalData('allQuestionsTable');
			var settings = allQuestionsTable.fnSettings();
			$('#categoryFilterAllQuestions').val(settings.aoPreSearchCols[0].sSearch);
			$('#ageCategoryFilterAllQuestions').val(settings.aoPreSearchCols[1].sSearch);			
	    },
	    "fnServerData": fnDataTablesPipeline,
	    "sAjaxSource" : '/rest_api/dt_allquestions.php',
	    "bServerSide" : true,
	    "sDom": '<"pager"pi>t<"pager"p>',
	    "aoColumns" : [ { "bSortable" : false }, // category dropdown
	                    { "bSortable" : false }, // age category dropdown
			    { "bSortable" : true, "sType" : "html" }, // question
			    { "bSortable" : true }, // answers
	                    { "bSortable" : false, "bVisible" : false } // question id
			  ],
	    "aaSorting" : [[3, 'desc']]   // sort on answers - highest # first
	});
	storeGlobalData('allQuestionsTable', allQuestionsTable);
	$('#categoryFilterAllQuestions').bind('change', {}, function () { // set up filtering on categories
	    //safelog('resorting allquestions on ' + this.value);
	    var allQuestionsTable = getGlobalData('allQuestionsTable');
	    allQuestionsTable.fnFilter(this.value, 0);
	});
	$('#ageCategoryFilterAllQuestions').bind('change', {}, function () { // set up filtering on categories
	    //safelog('resorting allquestions on ' + this.value);
	    var allQuestionsTable = getGlobalData('allQuestionsTable');
	    allQuestionsTable.fnFilter(this.value, 1);
	});
 	$('#navAll a').click(function(e) { 
 		e.preventDefault();
	    var allQuestionsTable = getGlobalData('allQuestionsTable');
	    allQuestionsTable.fnFilter('', 0);
	    allQuestionsTable.fnFilter('', 1); 		
 	});
    }
}

$(document).ready(function () {
	bindQuestionText();

	resetAllHints('input[hint], textarea[hint]');

	fixupBrokenAnchors();
 	$(window).scroll(function () { 
		moveScrollingAnchor();
 	});
 	
 	widgetPreview.init();
});

var widgetPreview = {
  width: 300,
  init: function() {
    $('#singlewidgetWidth').change(function () {
      widgetPreview.updateCode();
      widgetPreview.updatePreview();
    });
  },
  getCode: function(type) {
    var widgetWidth = $('#singlewidgetWidth option:selected').val();
    var widgetHeight = $('#tss_widget').height();
    var widgeturl = '';
    var widgetcode = '';
  	var params = {};
  	params['width'] = widgetWidth;
  	params['widgetOutlineColor'] = 'e34fb0'
  	params['widgetQuestionType'] = 'single'
  	params['widgetName'] = 'My%20Question';
  	params['widgetHtmlType'] = type;
  	params['singleid'] = questionID;
  	params['ver'] = '2';
  	
  	widgeturl = widgetPreview.generateWidgetURL(params);
    
    params = {};
    params['url'] = widgeturl;
    params['width'] = widgetWidth;
    params['height'] = widgetHeight;
    params['singleid'] = questionID;
    params['ver'] = '2';
    if (type == 'script')
      widgetcode = widgetPreview.generateWidget(params);
    else
      widgetcode = widgetPreview.generateIframe(params);
    
    return widgetcode;
  },
  generateIframe: function(params) {
    var code;
  	code =	'<div style="line-height:0;"><iframe id="tss_widget" src="' + params['url'] + '" width="' + params['width'] + '" height="' + params['height'] + '"  noresize="noresize" allowtransparency="true" frameborder="0" border="0" cellspacing="0" scrolling="no" marginwidth="0" marginheight="0" style="margin:0;padding:0;border:0;overflow:hidden;background-color:transparent;"></iframe>';
  	code += '<div style="text-align:center;line-height:14px;margin:0;padding:0;width:' + params['width'] + 'px;"><a href="http://' + http_host +  '/question/q/' + params['singleid'] + '" style="color:#000000;font-size:11px;font-family:sans-serif;text-decoration:underline;font-weight:normal;font-style:normal;">View this question on Skinnyscoop</a></div></div>\n';
  	
  	return code;
  },
  generateWidget: function(params) {
    var code;
    code = '<div style="line-height:0;"><'+'script src="' + params['url'] + '"></'+'script>';
    code += '<div style="text-align:center;line-height:14px;margin:0;padding:0;width:' + params['width'] + 'px;"><a href="http://' + http_host +  '/question/q/' + params['singleid'] + '" style="color:#000000;font-size:11px;font-family:sans-serif;text-decoration:underline;font-weight:normal;font-style:normal;">View this question on Skinnyscoop</a></div></div>\n';
    
    return code;
  },
  generateWidgetURL: function(params) {    
    var widgeturl = 'http://' + http_host + '/question/widget?alt=widget';
  	widgeturl += '&width=' + params['width'];
  	widgeturl += '&singleid=' + params['singleid'];
  	widgeturl += '&bgcolor=' + params['widgetOutlineColor'];
    widgeturl += '&type=' + params['widgetQuestionType'];
  	widgeturl += '&name=' + params['widgetName'];
  	widgeturl += '&format=' + params['widgetHtmlType'];
  	widgeturl += '&ver=' + params['ver'];

  	return widgeturl;
  },
  updateCode: function() {
    $('#embedcode').val(widgetPreview.getCode('script'));
  },
  updatePreview: function() {
    $('#widgetPreview').html(widgetPreview.getCode('iframe'));
    
    $('#embed_splash').css('width', parseFloat($('#singlewidgetWidth option:selected').val()) + 330 + 'px');
    $('#embed_splash').css('left', $('#embed_splash').position().left + (widgetPreview.width - parseFloat($('#singlewidgetWidth option:selected').val()))/2 + 'px');
    widgetPreview.width = parseFloat($('#singlewidgetWidth option:selected').val());
  }
}
