var KeywordStats = function(accToken) {
	var proxyUrl = '/wp-content/themes/SAT/KeywordStats/proxy.php';
	var accessToken = accToken;
	var accountId = null;
	var campaignId = null;
	var campaignKeywords = {};
	var adId = null;
	var adKeywords = {};
	var that = this;
	var url = '';
	var callback = null;
	
	var request = function(url, callback) {
		$.ajax({
			url: url,
			dataType: 'json',
			beforeSend: function() {
				showLoading();
			},
			success: callback
		});
	};
	
	var showLoading = function() {
		$('.table-area div').hide();
		$('.notification_error').hide();
		that.disableList('acc-select');
		that.disableList('com-select');
		that.disableList('ad-select');
		$('.notification').show();
	};
	
	var hideLoading = function() {
		$('.table-area div').hide();
	};
	
	var showError = function(error) {
		var errorMessage = '';
		
		switch (error) {
			case 'FACEBOOK_ERROR':
				errorMessage = 'Facebook error. <span class="try_again">Try again.</span>';
				break;
			case 'ARGUMENT_ERROR':
				errorMessage = 'Argument error. <span class="try_again">Try again.</span>';
				break;
			default:
				errorMessage = 'Communication error. <span class="try_again">Try again.</span>';
				break;
		}
		
		$('.notification').hide();
		$('.notification_error span').html(errorMessage);
		$('.notification_error .try_again').click(function() {
			request(url, callback);
		});
		$('.notification_error').show();
	};
	
	var emptyList = {"all" : "All"};
	
	this.disableList = function(name, shouldEmpty) {
		if (shouldEmpty) {
			$('#' + name).selectBox('options', emptyList);
		}
		$('.' + name).find('.trans').show();
	};
	
	this.populateTable = function(data) {
		$('.grid').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="table"></table>');
		$('#table').dataTable({
			"sDom": "prt",
	    	"sPaginationType": "full_numbers",
	    	"bFilter": false,
	    	"bInfo": false,
	    	"bLengthChange": false,
	    	"aaData": data,
	    	"aoColumns": [
	    		{"sTitle" : "keyword"},
	    		{"sTitle" : "imps"},
	    		{"sTitle" : "clicks"},
	    		{"sTitle" : "uimps"},
	    		{"sTitle" : "uclicks"},
	    		{
	    			"sTitle" : "ctr (%)",
	    			"fnRender": function(obj) {
		    			return obj.aData[5].toFixed(3);
	    			}
    			},
	    		{
		    		"sTitle" : "uctr (%)",
	    			"fnRender": function(obj) {
		    			return obj.aData[6].toFixed(3);
	    			}
	    		},
	    		{
		    		"sTitle" : "freq",
	    			"fnRender": function(obj) {
		    			return obj.aData[7].toFixed(1);
	    			}
	    		}
			]
		});
		$('#table').find('th').removeAttr('style');
		$('.grid').show();
	};	
	
	this.populateList = function(level) {
		switch (level) {
			case 'top':
				this.getAccounts();
				break;
			case 'account':
				this.getCampaigns();
				break;
			case 'campaign':
				this.getAdGroups();
				break;
			case 'ad_groups':
				this.getAdsKeywords();
				break;
			default:
				break;
		};
	};
	
	this.onAccChange = function(event) {
		accountId = $(this).val();
		if (accountId != 'all') {
			that.populateList('account');
		} else {
			that.disableList('com-select', true);
			that.disableList('ad-select', true);
			hideLoading();
			$('.big-arrow').show();
		}
	};
	
	this.onComChange = function() {
		campaignId = $(this).val();
		if (campaignId != 'all') {
			that.populateList('campaign');
		} else {
			campaignId = null;
			that.populateTable(campaignKeywords);
			that.disableList('ad-select');
		}
	};
	
	this.onAdChange = function() {
		adId = $(this).val();
		if (adId != 'all') {
			that.populateList('ad_groups');
		} else {
			adId = null;
			that.populateTable(adKeywords);
		}
	};
	
	$('#acc-select').bind('change', this.onAccChange);	
	$('#com-select').bind('change', this.onComChange);	
	$('#ad-select').bind('change', this.onAdChange);	
	
	this.getAccounts = function() {
		url = proxyUrl + '?f=accounts&accessToken=' + accessToken;
		callback = function(data) {
			var accountsList = '<option value="all" title="All">All</option>';
			if (data.status == 'ok') {
				if (data.accounts) {
					for (var i = 0; i < data.accounts.length; i++) {
						var obj = data.accounts[i];
						accountsList += '<option value="' + obj.id + '" title="' + obj.name + '">' + obj.name + '</option>';
					}
				}
				
				$('#acc-select').selectBox('options', accountsList);
				
				$('.acc-select').find('.trans').hide();
				hideLoading();
				$('.big-arrow').show();
			} else {
				showError(data.error);
			}
		};
		request(url, callback);
	};
	
	this.getCampaigns = function() {
		url = proxyUrl + '?f=campaigns&accessToken=' + accessToken + '&accountId=' + accountId;
		callback = function(data) {
			var campaignsList = '<option value="all" title="All">All</option>';
			if (data.status == 'ok') {
				if (data.campaigns) {
					for (var i = 0; i < data.campaigns.length; i++) {
						var obj = data.campaigns[i];
						campaignsList += '<option value="' + obj.id + '" title="' + obj.name + '">' + obj.name + '</option>';
					}
				}
				
				$('#com-select').selectBox('options', campaignsList);
						
				hideLoading();
				$('.acc-select, .com-select').find('.trans').hide();
				
				if (data.keywords) {
					var keywords = getKeywords(data.keywords);
					campaignKeywords = keywords;
					that.populateTable(keywords);
				}
			} else {
				showError(data.error);
			}
		};
		request(url, callback);
	};
	
	this.getAdGroups = function() {
		url = proxyUrl + '?f=ad_groups&accessToken=' + accessToken + '&accountId=' + accountId + '&id=' + campaignId;
		callback = function(data) {
			var adGroupsList = '<option value="all" title="All">All</option>';
			if (data.status == 'ok') {
				if (data.adgroups) {
					for (var i = 0; i < data.adgroups.length; i++) {
						var obj = data.adgroups[i];
						adGroupsList += '<option value="' + obj.id + '" title="' + obj.name + '">' + obj.name + '</option>';
					}
				}
				
				$('#ad-select').selectBox('options', adGroupsList);
						
				hideLoading();
				$('.acc-select, .com-select, .ad-select').find('.trans').hide();
				
				if (data.keywords) {
					var keywords = getKeywords(data.keywords);
					adKeywords = keywords;
					that.populateTable(keywords);
				}
			} else {
				showError(data.error);
			}
		};
		request(url, callback);
	};
	
	this.getAdsKeywords = function() {
		url = proxyUrl + '?f=ads_keywords&accessToken=' + accessToken + '&accountId=' + accountId + '&id=' + adId;
		callback = function(data) {
			var adGroupsList = '<option value="all" title="All">All</option>';
			if (data.status == 'ok') {
				if (data.adgroups) {
					for (var i = 0; i < data.adgroups.length; i++) {
						var obj = data.adgroups[i];
						adGroupsList += '<option value="' + obj.id + '" title="' + obj.name + '">' + obj.name + '</option>';
					}
				}
				
				hideLoading();
				$('.acc-select, .com-select, .ad-select').find('.trans').hide();
				
				if (data.keywords) {
					var keywords = getKeywords(data.keywords);
					that.populateTable(keywords);
				}
			} else {
				showError(data.error);
			}
		};
		request(url, callback);
	};
	
	var getKeywords = function(data) {
		var keywords = [];
		$.each(data, function(index, row) {
			var currentRow = [];
			
			$.each(row, function(key, value) {
				currentRow.push(value);
			});
			
			keywords.push(currentRow);
		});
		return keywords;
	};
};
