//Main Envato Mobile v2 Javascript
//Isn't snooping through code just a blast!
$(function(){
	//Create Login Cookie
	$('#loginButton').tap( function(e){
		$('#loginError').fadeOut('fast');
		var userName = $('#username').val();
		var apiKey = $('#apikey').val();
		var jsonURL = 'http://marketplace.envato.com/api/v1/'+userName+'/'+apiKey+'/vitals.json';
		
		$.ajax({
			type: "POST",
			url: "php/jsonGet.php",
			data: ({'jsonURL' : jsonURL, 'getType' : 'account'}),
			success: function(data) {
				if(data == 'error')
				{
					$('#loginError').fadeIn('fast');
				}
				else
				{
					if($('#rememberLogin').attr('checked') == true)
					{
						window.localStorage.setItem('envatomoblie_username', userName);
						window.localStorage.setItem('envatomoblie_apikey', apiKey);
					}
					accountLoad(userName, apiKey);
					
					$('#login').fadeOut('fast', function() {
						$('#accountPage').fadeIn('fast');
					});
				}
			} 
		});
	});
	
	/*
	$('a[target="_blank"]').livequery('click', function(event) { 
		if (confirm('This link opens in a new window.')) {
			return true;
		} else {
			$(this).removeClass('active');
			return false;
		}
	});
	*/
	
	//Market Page Scrolling
	$('a#recentLink').tap( function(e){
		$('html, body').animate({
		scrollTop: $("#recentItems").offset().top
		}, 2000);
	});
	
	$('a#popularLink').tap( function(e){
		$('html, body').animate({
		scrollTop: $("#popularItems").offset().top
		}, 2000);
	});
	
	$('a#popularAuthorLink').tap( function(e){
		$('html, body').animate({
		scrollTop: $("#popularAuthors").offset().top
		}, 2000);
	});
	
	//Get Selected market and load page
	$('a.marketButton').tap( function(e){
		$('#loadedPage').hide();
		$('#loading').html('Loading...');
		$('#loading').fadeIn('fast');
		
		var marketId = $(this).attr('id'); 
		$('#marketPage .subToolbar').attr('class', 'subToolbar '+marketId);
		if(marketId == "ocean")
		{
			marketId = "3docean";
		}
		$('#marketTitle').html($(this).text());
		
		var jsonURL = 'http://marketplace.envato.com/api/v1/popular:'+marketId+'+random-new-files:'+marketId+'.json';
		
		//Load API data
		$.ajax({
			type: "POST",
			url: "php/jsonGet.php",
			data: ({'jsonURL' : jsonURL, 'getType' : 'market'}),
			success: function(data) {
				if(data == 'error')
				{
					$('#loading').html('Error loading JSON.');
					
				}
				else
				{
					$('div#loadedPage').html(data);
					//Fade in Page
					$('#loading').fadeOut('fast', function() {
						$('#loadedPage').fadeIn('fast');
					});
				}
			},
		});
	});	
	
	//Form was acting up so tried different method
	//Kinda crude, should fix
    $('#searchForm input').keypress(function(e)
    {
		var code = (e.keyCode ? e.keyCode : e.which);
		if (code == 13)
		{		
			searchResults();
		}
    });
	
	$('input#searchButton').tap( function(e){
		searchResults();
	});
	
	//Get Search Results
	function searchResults() 
	{
		$('#search-loadedPage').hide();
		$('#search-loading').html('Loading...');
		$('#search-loading').fadeIn('fast');
		
		var marketId = $('#siteSelect').val(); 
		var searchTerm = $('#searchInput').val().replace(/ /g,'-');
		
		if(marketId == "ocean")
		{
			marketId = "3docean";
		}
		
		//$('#searchTitle').html($('#searchInput').val());
		
		var jsonURL = 'http://marketplace.envato.com/api/v1/search:'+marketId+',,'+searchTerm+'.json';
		
		//Load API data
		$.ajax({
			type: "POST",
			url: "php/jsonGet.php",
			data: ({'jsonURL' : jsonURL, 'getType' : 'search'}),
			success: function(data) {
				if(data == 'error')
				{
					$('#search-loading').html('Error loading JSON.');
					
				}
				else
				{
					$('div#search-loadedPage').html(data);
					//Fade in Page
					$('#search-loading').fadeOut('fast', function() {
						$('#search-loadedPage').fadeIn('fast');
					});
				}
			},
		});
	};	
	
	// For Forum Markets
	//Get Selected market and load forum page
	$('a.forumButton').tap( function(e){
		$('#forums-loadedPage').hide();
		$('#forums-loading').html('Loading...');
		$('#forums-loading').fadeIn('fast');
		
		var marketId = $(this).attr('id'); 
		$('#forums-marketPage .subToolbar').attr('class', 'subToolbar '+marketId);
		if(marketId == "ocean")
		{
			marketId = "3docean";
		}
		$('#forum-marketTitle').html($(this).text());
		
		var jsonURL = 'http://marketplace.envato.com/api/v1/active-threads:'+marketId+'.json';
		
		//Load API data
		$.ajax({
			type: "POST",
			url: "php/jsonGet.php",
			data: ({'jsonURL' : jsonURL, 'getType' : 'forum-market'}),
			success: function(data) {
				if(data == 'error')
				{
					$('#loading').html('Error loading JSON.');
					
				}
				else
				{
					$('div#forums-loadedPage').html(data);
					//Fade in Page
					$('#forums-loading').fadeOut('fast', function() {
						$('#forums-loadedPage').fadeIn('fast');
					});
				}
			},
		});
	});	
	
	//Account Orientation Change
	$('body').bind('turn', function(e, data){
    	if(data.orientation == "landscape")
    	{
    		$('#portrait').fadeOut('fast', function() {
				$('#landscape').fadeIn('fast');
			});
    	}
    	if(data.orientation == "profile")
    	{
    		$('#portrait').fadeIn('fast', function() {
				$('#landscape').fadeOut('fast');
			});
    	}
    });

	
	//Load Account Data
	$('a.accountButton').tap( function(e){
		var loginCheck = window.localStorage.getItem('envatomoblie_apikey');  // <-- Local storage!
		
		if(loginCheck == null)
		{
			$('#login').show();
			$('#accountPage').hide();
			
		}
		else
		{
			$('#accountPage').show();
			$('#login').hide();
			accountLoad(window.localStorage.getItem('envatomoblie_username'), window.localStorage.getItem('envatomoblie_apikey'));
		}
	});
	
	//Account Data Load Function
	function accountLoad(userName, apiKey)
	{
		var jsonURL = 'http://marketplace.envato.com/api/v1/'+userName+'/'+apiKey+'/vitals+recent-sales+account.json';
		
		//Load API data
		$.ajax({
			type: "POST",
			url: "php/jsonGet.php",
			data: ({'jsonURL' : jsonURL, 'getType' : 'account'}),
			success: function(data) {
				if(data == 'error')
				{
					$('#loadingAccount').html('Error loading JSON.');					
				}
				else
				{
					$('div#loadedPageAccount').html(data);
					//Fade in Page
					$('#loadingAccount').fadeOut('fast', function() {
						$('#loadingAccount').hide();
						$('#loadedPageAccount').fadeIn('fast');
					});
				}
			},
		});
		
		$('div#chart').html('<img width="480" height="263" src="php/makeChart.php?user='+userName+'&api='+apiKey+'">');
	}
	
	//Logout Function
	$('a.logout').tap( function(e){
		if (confirm('This will remove your stored login.')) {
			window.localStorage.removeItem('envatomoblie_username');
			window.localStorage.removeItem('envatomoblie_apikey');
			return true;
		} else {
			return false;
		}
		
	});
});