/**
 * JS File for Index Page
 */

// Set Global Vars
var reportInt;
var haveDomainReports = 0;
var haveKeywordReports = 0;
var listedReports = new Array();
var displayedReports = new Array();

// On Ready
$(function() {
	checkReportInputs();
});

function checkReportInputs ()
{
	var keywordRequired = false;
	
	$('#keywordInput').hide();
	$('.reportTypesKeyword').each(function (index, domEle) {			
		if ($(domEle).is(":checked"))
		{
			$('#keywordInput').show();
			$('#keywordIsRequired').html('Required');
			keywordRequired = true;
		}
	});
	
	$('#urlInput').hide();
	$('.reportTypesUrl').each(function (index, domEle) {			
		if ($(domEle).is(":checked"))
		{
			$('#urlInput').show();
		}
	});
	
	// Check if Keyword is Optional
	if ($('#reportType_6').is(":checked"))
	{
		$('#keywordInput').show();
		
		if (keywordRequired === false)
		{
			$('#keywordIsRequired').html('Optional');
		}
	}
}

function createReports (reportIds, keywordReports, domainReports)
{
	// Hide Slider
	$('#slider').hide();
	
	// Hide Sales Text
	$('#maincontent').hide();
	
	// Change CSS of Search Box
	$('#generateReports').css('margin', '105px auto 0 auto');
	
	// Change Background
	$('body').css('background', '#FCFCFC url(/images/secondary_bg.png) repeat-x');
	
	// Show Loading
	$('#loading').show();
	
	listedReports = reportIds.split(',');
	
	// Start Keyword Timer if these are Keyword Reports
	if (keywordReports == 1)
	{
		haveKeywordReports = 1;		
	}
	
	// Start Domain Timer if these are Domain Reports
	if (domainReports == 1)
	{
		haveDomainReports = 1;		
	}
	
	// Run Our Get Reports
	getReports();
	
	// Check Report Status
	reportInt = window.setInterval("getReports()", 3000);	
}

function endReports ()
{
	// Hide Loading
	$('#loading').hide();
	
	// End Timer
	reportInt = window.clearInterval(reportInt);
}

function getReports ()
{
	// Dont get reports already displayed
	$.each(displayedReports, function(key, val) {		
		listedReports = $.grep(listedReports, function(value) {
			return value != val;
		});
	});
	
	if (listedReports.length > 0)
	{
		$.getJSON('/ajax/getreports/reportIds/'+listedReports+'/needKeywordData/'+haveKeywordReports+'/needDomainData/'+haveDomainReports, function(results) {
			
			$.each(results, function(key, val) {
				if (val.statusId >= 2 && haveKeywordReports == 1)
				{
					haveKeywordReports = 0;
					
					// Update Keyword Data
					$('#keywordHolder').html(val.keyword);
					$('#monthlySearchesHolder').html(val.monthly_searches);
					$('#cpcHolder').html(val.cpc);
					$('#ppcHolder').html(val.ppc);
					
					$('#keywordDetails').show();
				}
				
				if (val.statusId >= 2 && haveDomainReports == 1)
				{
					haveDomainReports = 0;
					
					// Update Domain Data
					$('#domainName').html(val.domain);
					$('#thumbnail').attr('src', val.thumbnail);
					$('#thumbnail').attr('alt', val.domain);
					$('#googlePageRank').html(val.pagerank);
					$('#dmozListing').html(val.dmoz);
					$('#googleIndex').html(val.google_index);
					$('#alexaLinks').html(val.alexa_links);
					$('#authorityFlow').html(val.authority);
					$('#yahooDir').html(val.yahoo_dir);
					$('#bingIndex').html(val.bing_index);
					$('#deliciousLinks').html(val.delicious_links);
					$('#alexaRanking').html(val.alexa_ranking);
					$('#facebookPage').html(val.facebook);
					$('#domainAge').html(val.domain_age);
					$('#diggLinks').html(val.digg_links);
					
					// Build Pages Table
					$.each(val.urls, function(url_key, url_val) {
						$('#urlStats tr:last').after('<tr><td>'+url_val.url+'</td><td>'+url_val.pr+'</td><td>'+url_val.word_count+'</td><td>'+url_val.density+'</td></tr>');						
					});					
					
					$('#domainDetails').show();
				}
				
				if (val.statusId == 4)
				{
					$.getJSON('/ajax/scorereport/reportId/'+val.reportId, function(scoreResult) {
						displayedReports.push(val.reportId);
						
						$('#reportListings ul').append('<li>'+scoreResult+'/100 '+val.reportName+' (<a href="#" onclick="javascript:showReport('+val.reportId+')" title="'+val.reportDescription+'">Click to View Report</a>)</li>');
		
						$('#reportListings ul li a[title]').tooltip({ position: 'center right', opacity: 0.7, tipClass: 'tooltip2' });
												
						// Show Reports				
						$('#reportListings').show();												
					});
				}
			});		
		});
	}
	else
	{
		endReports();
	}
}

function showReport(reportId)
{
	if ($('#report' + reportId).length == 0)
	{
		// Need to move the Loading Box Down in the DOM
		$('#loading').appendTo('#reports');
		
		// Show Loading Screen
		$('#loading').show();		
		
		$.getJSON('/ajax/getreport/reportId/'+reportId, function(results) {
			
			if (results.template == 'Grid')
			{			
				// Get a New Copy of our template
				var template = $('#reportTemplate').clone();
				
				// Change ID
				template.attr('id', 'report' + reportId);
				
				// Append our Report to Reports
				$('#reports').append(template);
				
				// Set Close Action
				$('#report' + reportId + ' div.closeLink a').click(function() {
					  $('#report' + reportId).hide();
				});
				
				// Report Title
				$('#report' + reportId + ' h1').html(results.title);	
				
				// THead
				$('#report' + reportId + ' table thead').append('<tr>');
				$.each(results.cols, function(key, val) {
					$('#report' + reportId + ' table thead').append('<th title="'+val.description+'">'+val.name+'</th>');
				});
				$('#report' + reportId + ' table thead').append('</tr>');
				
				// TBody
				if (results.data.length > 0)
				{
					$.each(results.data, function(key, row) {
						$('#report' + reportId + ' table tbody').append('<tr>');
						
						$.each(row, function(key, val) {
							$('#report' + reportId + ' table tbody').append('<td>'+val+'</td>');
						});
						
						$('#report' + reportId + ' table tbody').append('</tr>');
					});
				}
				else
				{
					$('#report' + reportId + ' table tbody').append('<tr><td colspan="'+results.cols.length+'">No Data for this Report</td></tr>');
				}
				
				// TFoot
				$('#report' + reportId + ' table tfoot').append('<tr>');
				$.each(results.cols, function(key, val) {
					$('#report' + reportId + ' table tfoot').append('<th title="'+val.description+'">'+val.name+'</th>');
				});
				$('#report' + reportId + ' table tfoot').append('</tr>');			
	
				// Tooltips
				$('#report' + reportId + ' table th[title]').tooltip();
				
				// Hide Loading Screen
				$('#loading').hide();	
				
				// Show Our Report
				template.show();
			}
			else if (results.template == 'OnsiteAnalysis')
			{
				// Need to move the Onsite Report
				$('#onsiteReportTemplate').appendTo('#reports');
				
				// Change ID
				$('#onsiteReportTemplate').attr('id', 'report' + reportId);
				
				// Set Close Action
				$('#report' + reportId + ' div.closeLink a').click(function() {
					  $('#report' + reportId).hide();
				});
				
				// Report Title
				$('#report' + reportId + ' h1').html(results.title);
				
				// Display Report Data
				$('#redirectCheckResults').html(results.data.redirect.value);
				$('#redirectCheckTips').html(results.data.redirect.tip);
				
				$('#duplicateSiteCheckResults').html(results.data.duplicate.value);
				$('#duplicateSiteCheckTips').html(results.data.duplicate.tip);
				
				$('#h1CheckResults').html(results.data.h1check.value);
				$('#h1CheckTips').html(results.data.h1check.tip);
				
				$('#wordCountResults').html(results.data.words.value);
				$('#wordCountTips').html(results.data.words.tip);
				
				$('#linkRatioResults').html(results.data.wordratio.value);
				$('#linkRatioTips').html(results.data.wordratio.tip);
				
				$('#titleExistsResults').html(results.data.titlecheck.value);
				$('#titleExistsTips').html(results.data.titlecheck.tip);
				
				$('#uniqueTitleCheckResults').html(results.data.uniquetitles.value);
				$('#uniqueTitleCheckTips').html(results.data.uniquetitles.tip);
				
				$('#titleKeywordCheckResults').html(results.data.titlewordcheck.value);
				$('#titleKeywordCheckTips').html(results.data.titlewordcheck.tip);
				
				$('#descriptionExistsResults').html(results.data.descriptioncheck.value);
				$('#descriptionExistsTips').html(results.data.descriptioncheck.tip);
				
				$('#uniqueDescriptionCheckResults').html(results.data.uniquedescription.value);
				$('#uniqueDescriptionCheckTips').html(results.data.uniquedescription.tip);
				
				$('#altTagsCheckResults').html(results.data.missingalts.value);
				$('#altTagsCheckTips').html(results.data.missingalts.tip);
				
				$('#lastModifiedResults').html(results.data.lastmodified.value);
				$('#lastModifiedTips').html(results.data.lastmodified.tip);
				
				$('#lastModifiedRecentlyResults').html(results.data.lastmodifiedrecent.value);
				$('#lastModifiedRecentlyTips').html(results.data.lastmodifiedrecent.tip);
	
				// Tooltips
				$('#report' + reportId + ' h2[title]').tooltip();
				
				// Hide Loading Screen
				$('#loading').hide();	
				
				// Show Our Report
				$('#report' + reportId).show();				
			}
			else if (results.template == 'ContentAnalysis')
			{
			}
			else if (results.template == 'jqGrid')
			{
				// Need to move the Onsite Report
				$('#eAuthorityReportTemplate').appendTo('#reports');
				
				// Change ID
				$('#eAuthorityReportTemplate').attr('id', 'report' + reportId);
				
				// Set Close Action
				$('#report' + reportId + ' div.closeLink a').click(function() {
					  $('#report' + reportId).hide();
				});
				
				// Report Title
				$('#report' + reportId + ' h1').html(results.title);
				
				$("#list").jqGrid({
				    url: results.data.ajaxURL,
				    datatype: 'json',
				    mtype: 'POST',
				    colNames: results.data.colNames,
				    colModel: results.data.colModel,
				    pager: '#pager',
				    rowNum: results.data.defaultRows,
				    rowList: results.data.rowList,
				    sortname: results.data.defaultSortCol,
				    sortorder: results.data.defaultSortDir,
				    viewrecords: true,
				    gridview: true,
				    caption: results.data.caption,
				    width: 850
				}); 
				
				// Hide Loading Screen
				$('#loading').hide();	
				
				// Show Our Report
				$('#report' + reportId).show();	
			}
		});
	}
	else
	{
		$('#report' + reportId).show();		
	}
}

function useKRCoin (pageId, column)
{
	alert('Coming Soon');
}

