if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}

// initialize the moneyword matrix
var moneyWordMatrix = new Array(4);
for (i = 0; i < moneyWordMatrix.length; ++ i)
	moneyWordMatrix [i] = new Array(4);

moneyWordMatrix[0][0] = "POOR";
moneyWordMatrix[0][1] = "POOR";
moneyWordMatrix[0][2] = "POOR";
moneyWordMatrix[0][3] = "POOR";
moneyWordMatrix[1][0] = "GOOD";
moneyWordMatrix[1][1] = "FAIR";
moneyWordMatrix[1][2] = "FAIR";
moneyWordMatrix[1][3] = "POOR";
moneyWordMatrix[2][0] = "GOOD";
moneyWordMatrix[2][1] = "GOOD";
moneyWordMatrix[2][2] = "FAIR";
moneyWordMatrix[2][3] = "POOR";
moneyWordMatrix[3][0] = "GREAT";
moneyWordMatrix[3][1] = "GREAT";
moneyWordMatrix[3][2] = "GOOD";
moneyWordMatrix[3][3] = "POOR";

var tableStr;
var greatKws = [];
var goodKws = [];
var fairKws = [];
var poorKws = [];

function showKeywords(keywords) {
	jQuery("#keywords").val(keywords.join("\n"));
	jQuery("#keywords").show();
	jQuery("#keywords").select();
};

function showButtonPanel() {
	var disableBtn = function(keywords, button) {
		if (keywords.length === 0) {
			button.attr('disabled', 'disabled');
		}
		else
		{
			button.removeAttr('disabled');
		}
	};
	
	disableBtn(greatKws, jQuery('#greatKws'));	
	disableBtn(goodKws, jQuery('#goodKws'));	
	disableBtn(fairKws, jQuery('#fairKws'));	
	disableBtn(poorKws, jQuery('#poorKws'));	
	jQuery("#buttonPanel").show();
}

jQuery(document).ready(function() {

	// doesn't seem to work unless I call this first.  weird?
	jQuery.csv();
	jQuery("#keywords").hide();
	jQuery("#buttonPanel").hide();
	
	jQuery("#greatKws").click(function() {
		showKeywords(greatKws);
	});
	
	jQuery("#goodKws").click(function() {
		showKeywords(goodKws);
	});
	
	jQuery("#fairKws").click(function() {
		showKeywords(fairKws);
	});
	
	jQuery("#poorKws").click(function() {
		showKeywords(poorKws);
	});
	
	jQuery("#uploadform").uploadify({
		'uploader' : '/uploadify/uploadify.swf',
		'script' : '/uploadify/uploadify.php',
		'folder' : '/uploads',
		'queueID' : 'fileQueue',
		'fileDesc' : '*.csv',
		'fileExt' : '*.csv',
		'auto' : true,
		'cancelImg' : '/uploadify/cancel.png',
		onComplete : function(event, queueID, fileObj, response) {
			jQuery.get('/uploads/'+response, function(data) {
				// clear old data
				jQuery("#data").empty();
				jQuery("#buttonPanel").hide();
				jQuery("#keywords").hide();
				
				parseCSV(data);
				deleteFile(response);
			});
			
		}
	});
	
	function deleteFile(fileName)
	{
		jQuery.get('/uploadify/delete.php', { name: fileName });
	}
	
	function calculateScore(searches, comp)
	{
		var searchIndex = -1;
		var compIndex = -1;
		
		searches = parseInt(searches);
		comp = parseInt(comp);
		
		if (isNaN(searches) || isNaN(comp))
			return "-";
		
		if (searches <= 10)
			searchIndex = 0;
		else if (searches > 10 && searches <= 20)
			searchIndex = 1;
		else if (searches > 20 && searches <= 50)
			searchIndex = 2;
		else if (searches > 50)
			searchIndex = 3;

		if (comp <= 10000)
			compIndex = 0;
		else if (comp > 10000 && comp <= 30000) 
			compIndex = 1;
		else if (comp > 30001 && comp <= 75000)
			compIndex = 2;
		else if (comp > 75000)
			compIndex = 3;
			

		return moneyWordMatrix[searchIndex][compIndex];
	}
	
	function parseCSV(csvString) {
		var parsedCSV = jQuery.csv()(csvString);
		headers = parsedCSV[0];
		
		var keywordIndex = 0;
		var searchExactIndex = headers.indexOf("Searches (Exact)");
		var seoCompIndex = headers.indexOf("SEO Comp");
		
		if (searchExactIndex === -1)
		{
			var invalidFileStr = "<p style='color:red'><em>Invalid Market Samurai export file. Make sure your analyze your keywords with the <strong>Total Searches</strong> column enabled.</em></p>";
			jQuery("#data").append(invalidFileStr);
			return;
		}
		
		if (seoCompIndex === -1)
		{
			var invalidFileStr = "<p style='color:red'><em>Invalid Market Samurai export file. Make sure your analyze your keywords with the <strong>SEO Comp</strong> column enabled.</em></p>";
			jQuery("#data").append(invalidFileStr);
			return;
		}
		
		tableStr = "<table class='datatable'><thead><tr><th>Keyword</th><th>Daily Searches</th><th>"+headers[seoCompIndex]+"</th><th>Score</th></tr></thead><tbody>";
		for (var i = 1; i < parsedCSV.length; i++)
		{
			var score = calculateScore(parsedCSV[i][searchExactIndex], parsedCSV[i][seoCompIndex]);
			tableStr += "<tr class="+score+"><td>"+parsedCSV[i][keywordIndex]+"</td>";
			tableStr += "<td class='digits'>"+parsedCSV[i][searchExactIndex]+"</td>";
			tableStr += "<td class='digits'>"+parsedCSV[i][seoCompIndex]+"</td>";
			tableStr += "<td>"+score+"</td></tr>"
			
			
			if (score === "GREAT")
			{
				greatKws.push(parsedCSV[i][keywordIndex]);
			}
			else if (score === "GOOD")
			{
				goodKws.push(parsedCSV[i][keywordIndex]);
			}
			else if (score === "FAIR")
			{
				fairKws.push(parsedCSV[i][keywordIndex]);
			}
			else if (score === "POOR") 
			{
				poorKws.push(parsedCSV[i][keywordIndex]);
			}
		}
		
		tableStr += "</tbody></table>";	
			
		jQuery("#data").append(tableStr);
		jQuery(".datatable").tablesorter({
			headers: {
				3: {
					sorter:'score'
				}
			},
			sortList: [[3,1]]
		});
		showButtonPanel();
		//jQuery("#datatable").tablesorter().tablesorterPager({container: $("#pager"), size: 25}); 
		
	}

});

// add parser through the tablesorter addParser method 
jQuery.tablesorter.addParser({ 
    // set a unique id 
    id: 'score', 
    is: function(s) { 
        // return false so this parser is not auto detected 
        return false; 
    }, 
    format: function(s) { 
        // format your data for normalization 
        return s.toLowerCase().replace(/great/,3).replace(/good/,2).replace(/fair/,1).replace(/poor/,0); 
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
}); 

