// Selfy Variables
var faceType = 0;
var hairType = 0;
var accefType = 0;
var accehType = 0;
var topType = 0;
var bottomType = 0;
var backType = 0;
var hatType = 0;
var accenType = 0;
var shoeType = 0;
var coatType = 0;
var fgType = 0;
var fg2Type = 0;
var bgType = 0;
var bodycolorType = 17000192;
// Content Vars
var currentSelfyBox = 1;
var filterWindow = 0;
var searchWindow = 0;
var totalPages;
var ajaxBusy = 0;

// Feature Vars
var recentlyEquipped = [];
var selectedTypes = '';
var selectedColors = '';
var selectedGacha = '';
var currentSearch = '';
var isCC = 1;
var isGC = 1;
var isSL = 1;
var isNotSL = 1;
var isCS = 1;
var isNotCS = 1;
var isCAM = 1;
var isNotCAM = 1;
var isANI = 1;
var isNotANI = 1;
var mouse_is_inside;
var editingThisSelfy = 0;

// Warnings
var showedFilterWarning = '';
$(document).ready(function() {
	
	updateSelfy();
	$('#allTypes').click(function(){
		if($('#allTypes').is(':checked'))
		{
			$('.filterType').addClass('selected');
		}
		else
		{
			$('.filterType').removeClass('selected');
		}
		updateFilters();
	});
	
	$('#allGachas').click(function(){
		if($(this).is(':checked'))
		{
			$('#gachaSelect').attr('disabled','disabled');
		}
		else
		{
			$('#gachaSelect').removeAttr('disabled');
		}
		updateFilters();
	});
	
	$('.filterType').click(function() {
		if($(this).hasClass('selected'))
		{
			$(this).removeClass('selected');
		}
		else
		{
			$(this).addClass('selected');
		}
		
		if($('#allTypes').is(':checked'))
		{
			$('#allTypes').attr('checked', false);
		}
		updateFilters();
	});
	
	$('.extraCheckbox').click(function(){
		updateFilters();
	});
	
	getItems();
	
	$('#nextPage').click(function(){
		paging('next');
	});
	
	$('#backPage').click(function(){
		paging('back');
	});
	
	$('#firstPage').click(function(){
		paging('first');
	});
	
	$('#lastPage').click(function(){
		paging('last');
	});
	
	$('.equippedItem').click(function(){
		var imgSrc;
		var typeFound = $(this).attr('name');
		if(typeFound == 'bg')
		{
			typeFound = 'bg1';
		}
		eval($(this).attr('name')+'Type=0;');
		updateSelfy();
		if(($(this).attr('name') == 'fg') || ($(this).attr('name') == 'fg2'))
		{
			imgSrc = 'http://plustg.com/v2/_img/'+typeFound+'.png'
		}
		else
		{
			imgSrc = 'http://www.tiniergoodies.com/v2/_img/'+typeFound+'.png'
		}
		$('img[name="'+$(this).attr('name')+'"]').attr({
			'src': imgSrc,
			'alt':		'Unequipped',
			'title':	'Unequipped'
		});
	});
	
	$('#curPage').bind('keypress', function(e) {
		if(e.keyCode == 13)
		{
			if($('#curPage').val() <= totalPages)
			{
				if($('#curPage').val() < 1)
				{
					$('#curPage').text(1);
					getItems(1);
				}
				else
				{
					getItems($('#curPage').val());
				}				
			}
			else
			{
				$('#curPage').text(totalPages);
				getItems(totalPages);
			}
			
		}
	});
	
	$('#itemSearch').bind('keypress', function(e){
		if(e.keyCode == 13)
		{
			currentSearch = $('#itemSearch').val();
			if(selectedTypes != '')
			{
				if(selectedColors == '')
				{
					if(!showedFilterWarning)
					{
						showNotification('Error','Until you cleared your search, only colors will work. (This message will only show once)');
						showedFilterWarning = '1';
					}
					getItems(undefined, undefined, undefined, undefined, currentSearch);
				}
				else
				{
					if(!showedFilterWarning)
					{
						showNotification('Error','Until you cleared your search, only colors will work. (This message will only show once)');
						showedFilterWarning = '1';
					}
					getItems(undefined, undefined, undefined, selectedColors, currentSearch);
				}
			}
			else
			{
				getItems(undefined, undefined, undefined, selectedColors, currentSearch);
			}
		}
	});
	
	$('#colors > li > div').click(function(){
		if($(this).attr('class') != 'colorSelected')
		{
			$(this).attr('class', 'colorSelected');
		}
		else
		{
			$(this).attr('class', '');
		}
		
		updateFilters();
	});
	
	$('#gachaSelect').change(function(){
	    updateFilters();
	});
	
	$('#filterWindow').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(!mouse_is_inside)
        {
        	filterWindow = 0;
        	$('#filterWindow').hide();
        }
    });
});

function updateSelfy()
{
	var movieStr = 'http://img.tinierme.com/selfy.swf?face='+faceType+
	  '&hair='+hairType+
	  '&accef='+accefType+
	  '&acceh='+accehType+
	  '&top='+topType+
	  '&bottom='+bottomType+
	  '&accen='+accenType+
	  '&back='+backType+
	  '&hat='+hatType+
	  '&shoe='+shoeType+
	  '&coat='+coatType+
	  '&bg='+bgType+
	  '&fg='+fgType+
	  '&fg2='+fg2Type+
	  '&bodycolor='+bodycolorType+
	  '&mode=fitting';
	  var flashvars = {};
	  var params = {
			bgcolor: '#ffffff',
	        allowScriptAccess: 'always',
	        movie: movieStr,
	        menu: 'false',
	        quality: 'high',
	        wmode: 'transparent'
	  };
	  var attributes = {};

	  swfobject.embedSWF(movieStr,
		'selfyCharacter',
		'231',
		'275',
		'9.0.0',
		0,
		flashvars,
		params,
		attributes);
}

function updateType(type, id)
{
	window[type + 'Type'] = id;
	updateSelfy();
}

function toggleSelfyEquips(button)
{
	if(button != currentSelfyBox)
	{
		switch(button)
		{
			case '1':
				$('#selfyLink').attr('class','active');
				$('#historyLink').attr('class','');
				$('#equippedLink').attr('class','');
				
				$('#selfyContainer').show();
				$('#selfyEquipped').hide();
				$('#selfyHistory').hide();
				currentSelfyBox = 1;
			break;
			case '2':
				$('#selfyLink').attr('class','');
				$('#historyLink').attr('class','');
				$('#equippedLink').attr('class','active');
				
				$('#selfyContainer').hide();
				$('#selfyEquipped').show();
				$('#selfyHistory').hide();
				currentSelfyBox = 2;
			break;
			case '3':
				$('#selfyLink').attr('class','');
				$('#historyLink').attr('class','active');
				$('#equippedLink').attr('class','');
				
				$('#selfyContainer').hide();
				$('#selfyEquipped').hide();
				$('#selfyHistory').show();
				currentSelfyBox = 3;
			break;
			default:
				$('#selfyLink').attr('class','active');
				$('#historyLink').attr('class','');
				$('#equippedLink').attr('class','');
				
				$('#selfyContainer').show();
				$('#selfyEquipped').hide();
				$('#selfyHistory').hide();
				currentSelfyBox = 1;
			break;
		}
	}
}

function toggleFilterWindow()
{
	if(filterWindow == 0)
	{
		if(searchWindow == 1)
		{
			$('#searchWindow').hide();
			searchWindow = 0;
		}
		$('#filterWindow').show();
		filterWindow = 1;
	}
	else
	{
		$('#filterWindow').hide();
		filterWindow = 0;
	}
}

function clearSearch()
{
	$('#itemSearch').attr('value','');
	currentSearch = '';
	getItems(undefined, selectedTypes, selectedGacha, selectedColors, currentSearch);
}

/*function toggleSearchWindow()
{
	if(searchWindow == 0)
	{
		if(filterWindow == 1)
		{
			$('#filterWindow').hide();
			filterWindow = 0;
		}
		$('#searchWindow').show();
		searchWindow = 1;
	}
	else
	{
		$('#searchWindow').hide();
		searchWindow = 0;
	}
}*/

function getItems(page, types, gacha, colors, search)
{
	if(ajaxBusy == 0)
	{
		ajaxBusy = 1;
		$('#itemListing').html('');
		
		// Define Default Values
		page = typeof(page) != 'undefined' ? page : 1;
		types = typeof(types) != 'undefined' ? types : '';
		gacha = typeof(gacha) != 'undefined' ? gacha : '';
		colors = typeof(colors) != 'undefined' ? colors : '';
		search = typeof(search) != 'undefined' ? search : '';
		// Set curPage
		$('#curPage').val(page);
		// Build up data string for ajax query
		var dataStr = 'types='+types+'&gachas='+gacha+'&colors='+colors+'&isCC='+isCC+'&isGC='+isGC+'&isSL='+isSL+'&isNotSL='+isNotSL+'&isCS='+isCS+'&isNotCS='+isNotCS+'&isCAM='+isCAM+'&isNotCAM='+isNotCAM+'&isANI='+isANI+'&isNotANI='+isNotANI+'&search='+search+'&page='+page;
		
		$.ajax({
			type: 'POST',
			url: 'http://plustg.com/v2/_inc/_php/_ajax/getItems.php',
			data: dataStr,
			dataType: 'xml',
			success: function(xml){
				if($(xml).find('total').text() == 0)
				{
					$('#itemListing').html('No items found.');
					totalItems = 0;
					lastPage(totalItems);
				}
				else
				{
					var totalItems = $(xml).find('total').text();
					lastPage(totalItems);
					
					$(xml).find('item').each(function(){
						var itemType = returnType($(this).find('type').text());
						var itemId = $(this).find('id').text();
						var itemName = $(this).find('name').text();			
						buildItem(itemType, itemId, itemName, '#itemListing');
					});
					
				}
				ajaxBusy = 0;
			}
		});
	}
	else
	{
		showNotification('Success','Please wait while we handle your last request.');
	}
}

function buildItem(itemType, itemId, itemName, appendDest)
{
	var className = '';
	var divName = 'oneItem';
	if(appendDest == '#selfyHistory')
	{
		className = 'equippedItem';
		divName = 'equippedItemContainer';		
	}
	
	var oneItem = $('<div />', {
		'class':divName
	});
	$('<img />', {
		'src':		'http://img1.tiniergoodies.com/_items/'+itemType+'_'+itemId+'_shop.png',
		'alt':		itemName,
		'title':	itemName,
		'class': className,
		click:		function(){
			eval(itemType+'Type='+itemId+';');
			updateSelfy();
			$('img[name="'+itemType+'"]').attr({
				'src': 'http://img1.tiniergoodies.com/_items/'+itemType+'_'+itemId+'_shop.png',
				'alt':		itemName,
				'title':	itemName
			});
			if(appendDest == '#itemListing')
			{
				doHistory(itemType, itemId, itemName);
			}
			else
			{
				
			}
		}
	}).appendTo(oneItem);
	
	$(oneItem).appendTo(appendDest);
}

function doHistory(itemType, itemId, itemName)
{
	var oneEquipped = [itemType,itemId,itemName];
	$('#selfyHistory').html('');
	
	var arrayHack = false;
	$(recentlyEquipped).each(function(){
	if(arrayHack == false)
	{
		if(in_array(oneEquipped[1], this))
		{
			arrayHack = true;
		}
	}
	});
	
	if(!arrayHack)
	{
		recentlyEquipped.push(oneEquipped);
	}
	
	$(recentlyEquipped).each(function()
	{
		var currentType = this[0];
		var currentId = this[1];
		var currentName = this[2];
		
		buildItem(currentType, currentId, currentName, '#selfyHistory');
	});
}

function lastPage(totalItems)
{
	totalItems = parseInt(totalItems);
	var totalCalc = totalItems / 28;
	totalPages = Math.ceil(totalCalc);
	
	
}

function paging(func)
{
	
	if(func == 'first')
	{
		if(parseInt($('#curPage').val()) != 1)
		{
			if(currentSearch != '')
			{
				getItems(1, undefined, undefined, selectedColors, currentSearch);
			}
			else
			{
				getItems(1, selectedTypes, selectedGacha, selectedColors, undefined);
			}
		}		
	}
	
	if(func == 'next')
	{
		if(parseInt($('#curPage').val()) < totalPages)
		{
			var nextPage = parseInt($('#curPage').val()) + 1;
			if(currentSearch != '')
			{
				getItems(nextPage, undefined, undefined, selectedColors, currentSearch);
			}
			else
			{
				getItems(nextPage, selectedTypes, selectedGacha, selectedColors, undefined);
			}
		}
	}
	
	if(func == 'back')
	{
		if(parseInt($('#curPage').val()) > 1)
		{
			var nextPage = parseInt($('#curPage').val()) - 1;
			if(currentSearch != '')
			{
				getItems(nextPage, undefined, undefined, selectedColors, currentSearch);
			}
			else
			{
				getItems(nextPage, selectedTypes, selectedGacha, selectedColors, undefined);
			}
		}
	}
	
	if(func == 'last')
	{
		if(parseInt($('#curPage').val()) < totalPages)
		{
			var nextPage = totalPages;
			if(currentSearch != '')
			{
				getItems(nextPage, undefined, undefined, selectedColors, currentSearch);
			}
			else
			{
				getItems(nextPage, selectedTypes, selectedGacha, selectedColors, undefined);
			}
		}
	}
}

function returnType(id)
{
	switch(id)
	{
		case '1':
			return 'face';
		break;
		case '2':
			return 'hair';
		break;
		case '3':
			return 'accef';
		break;
		case '4':
			return 'acceh';
		break;
		case '5':
			return 'top';
		break;
		case '6':
			return 'bottom';
		break;
		case '7':
			return 'back';
		break;
		case '8':
			return 'hat';
		break;
		case '9':
			return 'accen';
		break;
		case '10':
			return 'shoe';
		break;
		case '11':
			return 'coat';
		break;
		case '12':
			return 'bg';
		break;
		case '14':
			return 'fg';
		case '15':
			return 'fg2';
		break;
	}
}

function returnTypeId(typeName)
{
	switch(typeName)
	{
		case 'face':
			return 1;
		break;
		case 'hair':
			return 2;
		break;
		case 'accef':
			return 3;
		break;
		case 'acceh':
			return 4;
		break;
		case 'top':
			return 5;
		break;
		case 'bottom':
			return 6;
		break;
		case 'back':
			return 7;
		break;
		case 'hat':
			return 8;
		break;
		case 'accen':
			return 9;
		break;
		case 'shoe':
			return 10;
		break;
		case 'coat':
			return 11;
		break;
		case 'bg':
			return 12;
		case 'fg':
			return 14;
		case 'fg2':
			return 15;
		break;
	}	
}

function changeBody(id)
{
  bodycolorType = id;
  updateSelfy();
}

function updateFilters()
{
	// Find Selected Colors
	var totalColorsSelected = $('#colors > li > div.colorSelected').length;
	
	// Build Selected Colors
	if(totalColorsSelected != 0)
	{
		var tempStr = '';
		var countStr = 1;
		$('#colors > li > div.colorSelected').each(function(){
			var colorId = $(this).attr('id')
			colorId = colorId.replace(/color/i, "");
			
			if(countStr == 1)
			{
				
				tempStr = colorId;
			}
			else
			{
				tempStr = tempStr + ',' + colorId;
			}

			countStr++;
		});
		selectedColors = tempStr;
	}
	else
	{
		selectedColors = '';
	}
	
	// Find Selected Types
	var totalTypesSelected = $('img.filterType').hasClass('selected').length;
	if(totalTypesSelected != 0)
	{
		var tempStr = '';
		var countStr = 1;
		$('img.filterType').each(function(){
			if($(this).hasClass('selected'))
			{
				var typeId = returnTypeId($(this).attr('id'));
				if(countStr == 1)
				{
					
					tempStr = typeId;
				}
				else
				{
					tempStr = tempStr + ',' + typeId;
				}
				countStr++;
			}
		});
		selectedTypes = tempStr;
	}
	else
	{
		selectedTypes = '';
	}
	
	var totalExtrasSelected = $('input.extraCheckbox:checked').length;
	
	// Get Extra's Selected
	if(totalExtrasSelected != 0)
	{
		$('input.extraCheckbox').each(function(){
			switch($(this).attr('id'))
			{
				case 'chibiC':
					if($(this).is(':checked'))
					{
						isCC = 1;
					}
					else
					{
						isCC = 0;
					}
				break;
				case 'gachaC':
					if($(this).is(':checked'))
					{
						isGC = 1;
					}
					else
					{
						isGC = 0;
					}
				break;
				case 'completeSheet':
					if($(this).is(':checked'))
					{
						isCS = 1;
					}
					else
					{
						isCS = 0;
					}
				break;
				case 'normalSheet':
					if($(this).is(':checked'))
					{
						isNotCS = 1;
					}
					else
					{
						isNotCS = 0;
					}
				break;
				case 'superGacha':
					if($(this).is(':checked'))
					{
						isSL = 1;
					}
					else
					{
						isSL = 0;
					}
				break;
				case 'normalGacha':
					if($(this).is(':checked'))
					{
						isNotSL = 1;
					}
					else
					{
						isNotSL = 0;
					}
				break;
				case 'animated':
					if($(this).is(':checked'))
					{
						isANI = 1;
					}
					else
					{
						isANI = 0;
					}
				break;
				case 'nonAnimated':
					if($(this).is(':checked'))
					{
						isNotANI = 1;
					}
					else
					{
						isNotANI = 0;
					}
				break;
				case 'campaignItem':
					if($(this).is(':checked'))
					{
						isCAM = 1;
					}
					else
					{
						isCAM = 0;
					}
				break;
				case 'normalItem':
					if($(this).is(':checked'))
					{
						isNotCAM = 1;
					}
					else
					{
						isNotCAM = 0;
					}
				break;
			}
		});
	}
	else
	{
		isCC = 1;
		isGC = 1;
		isSL = 1;
		isNotSL = 1;
		isCS = 1;
		isNotCS = 1;
		isCAM = 1;
		isNotCAM = 1;
		isANI = 1;
		isNotANI = 1;
	}
	
	// Get Gacha Selected
	var gachaId = '';
	if($('#allGachas').is(':checked'))
	{
		var gachaId = 'all';
	}
	else
	{
		var gachaId = $('#gachaSelect > option:selected').val();
	}
	if(gachaId != 'all')
	{
		selectedGacha = gachaId;
	}
	else
	{
		selectedGacha = ''
	}
	if(!currentSearch)
	{
		getItems(undefined, selectedTypes, selectedGacha, selectedColors, currentSearch);
	}
	else
	{
		if(!showedFilterWarning)
		{
			showNotification('Error','Until you cleared your search, only colors will work. (This message will only show once)');
			showedFilterWarning = '1';
		}
		
		getItems(undefined, undefined, undefined, selectedColors, currentSearch);
	}
	
}

function saveAvatar()
{
	var editStr = '';
	if(editingThisSelfy != 0)
	{
		editStr = '&edit='+editingThisSelfy;
	}
	
    $.ajax({
    type: "POST",
    url: "http://plustg.com/v2/_inc/_php/_ajax/saveSelfy.php",
    data: "face="+faceType+
    "&hair="+hairType+
    "&accef="+accefType+
    "&acceh="+accehType+
    "&top="+topType+
    "&bottom="+bottomType+
    "&accen="+accenType+
    "&back="+backType+
    "&hat="+hatType+
    "&shoe="+shoeType+
    "&coat="+coatType+
    "&bodycolor="+bodycolorType+
    "&bg="+bgType+
    "&fg="+fgType+
    "&fg2="+fg2Type+
    editStr,
    success: function(xml) {
        if($(xml).find('success').text() != 0)
        {
        	window.location = "http://plustg.com/dream/"+$(xml).find('message').text()+"/share/";
        }
        else
        {
        	alert($(xml).find('message').text());
        }
    }
    });
}

function in_array (needle, haystack, argStrict) 
{
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                return true;
            }
        }
    }
     return false;
}
