//-----------------------------------------------------------
// Public JS
//-----------------------------------------------------------
var hg = [];

hg.BoutiqueSection = 1;

hg.TrackItem = function(itemTracked){
	var myVars = {
		'IDX' : 'item.track',
		'ItemTracked' : itemTracked
	};
	xh.postResponse('/', myVars);
}

hg.ShowGalleryImage = function(imagePath, width, height, caption){
	var ImageFile	= dom.$('DisplayImage').src.split('/');
	var ArrayLength	= ImageFile.length;
	OrigImageFile	= ImageFile[ArrayLength - 1];

	ImageFile		= imagePath.split('/');
	ArrayLength		= ImageFile.length;
	NewImageFile	= ImageFile[ArrayLength - 1];

	if(OrigImageFile == NewImageFile){
		return(true);

	}

	// update the image background
	if(width > height){
		// landscape
		dom.$('GalleryImage').className = 'ImageLandscape';
	}else{
		// portrait
		dom.$('GalleryImage').className = 'ImagePortrait';
	}

	// update the image
	dom.$('DisplayImage').src = imagePath;
	dom.$('DisplayImage').width = width;
	dom.$('DisplayImage').height = height;
/*	dom.$('DisplayImage').width = 1;
	dom.$('DisplayImage').height = 1;
	dom.$('DisplayImage').onload = function(){
		this.width = width;
		this.height = height;
	}
*/
	if(trim(caption) == ''){
		// hide caption
		dom.$('ImageCaption').style.display = 'none';
		dom.$('CaptionBamboo').style.display = 'none';
	}else{
		// update and display the caption
		dom.$('ImageCaption').innerHTML = caption;
		dom.$('ImageCaption').style.display = 'block';
		// Set Bamboo to display none untill a proper design is submitted [BD]
		dom.$('CaptionBamboo').style.display = 'none';
	}
	if(arguments[4] != null){
		hg.CurrentAlbumImage = arguments[4];
	}
}

hg.FlipImage = function(Direction){
	CurrentAlbumImage = hg.CurrentAlbumImage;
	AlbumImageObject = hg.AlbumImageObject;

	if(AlbumImageObject.length == 0){
		alert('This album is empty');
	}else{
		var TheNumber = null;
		if(Direction == 'prev' && CurrentAlbumImage == 0){
			TheNumber = AlbumImageObject.length - 1;
		}else if(Direction == 'next' && CurrentAlbumImage == (AlbumImageObject.length - 1)) {
			TheNumber = 0;
		}

		if(TheNumber == null){
			if(Direction == 'next'){
				TheNumber = (CurrentAlbumImage * 1) + 1;
			}else{
				TheNumber = (CurrentAlbumImage * 1) - 1;
			}
		}
		CurrentAlbumImage = TheNumber;
		var imagePath = AlbumImageObject[TheNumber]['Path'] + '/' + AlbumImageObject[TheNumber]['ImageID'] + '.' + AlbumImageObject[TheNumber]['Ext'];
		hg.ShowGalleryImage(imagePath, AlbumImageObject[TheNumber]['Width'], AlbumImageObject[TheNumber]['Height'], AlbumImageObject[TheNumber]['Caption']);
		hg.CurrentAlbumImage = CurrentAlbumImage;
	}
}

hg.AddToCart = function(itemID){
	$('.CartMessage').html('<img src="/images/e1/t1/ajx.load.round.gif" />');
	var myVars = {
		'IDX'	 : 'cart.process',
		'Action' : 'AddToCart',
		'ItemID' : itemID,
		'Rand'	 : Math.random()
	};
	$.post('/', myVars, hg.AddToCartCallback);
}

hg.AddToCartCallback = function(myReturn){
	myReturn = myReturn.split('|');
	if(myReturn[0] == 'ADDED') {
		$('.CartMessage').html('');
		$('#AddToCart' + myReturn[1]).remove();
		$('#Item' + myReturn[1] + ' .Cost').remove();
		$('#Item' + myReturn[1]).append('<div class="LavaDropAdded" style="margin: -32px 0px 0px 38px;"><img src="/img/e1/t1/starfishave.avatar.added.png" width="76" height="46" style="behavior: url(\'/css/e1/t1/iepngfix.htc\'); width: 76px; height: 46px; " /></div>');
	}
	else
		$('.CartMessage').html(myReturn[0]);
}

hg.addAvatar = function(characterTypeID) {
	if(arguments[1] != null)
		var parentID = arguments[1];

	$.post('/', 
		{
			'IDX'				: 'cart.process',
			'Action'			: 'AddAvatarToCart',
			'AvatarSelected'	: characterTypeID
		}, 
		function(data) {
			data = data.split('|');
			if (parentID != null && data[1] != null && data[1] == 'ADDED'){
				if ( data[0] == 'AllAdded' ) {
					$('.AvatarItem .AddedItAvatar').remove();
					$('.AvatarItem').append('<div class="AddedItAvatar"></div>');
				} else {
					$('#' + parentID).append('<div class="AddedItAvatar"></div>');
				}
			} else {
				$('.CartMessage').html(data[0]);			
			}
		}
	);
};


hg.EmptyCart = function(){
	if(confirm('Are you sure you want to empty all the items in your basket?')){
		$('.CartMessage').html('');
		var myVars = {
			'IDX'	 : 'cart.process',
			'Action' : 'EmptyCart',
			'Rand'	 : Math.random()
		};
		$.post( '/', myVars, hg.EmptyCartCallback );
	}else{
		return(false);
	}
}

hg.EmptyCartCallback = function(myReturn){
	window.location.href='/starfishave/';
}

hg.RemoveItem = function(type, itemID) {
	var confirmMsg	= 'Are you sure you want to remove this item from your basket?';
	confirmMsg		+= (type == 'Avatar') ? '\n Note: any items in your basket associated with this avatar will also be removed.': '';
	if(confirm(confirmMsg)) {
		$('.CartMessage').html('<img src="/images/e1/t1/ajx.load.round.gif" />');
		type = (type != 'Avatar' && type != 'Wallpaper') ? 'Item' : type;
		var myVars = {
			'IDX'	 : 'cart.process',
			'Action' : 'Remove' + type,
			'ItemID' : itemID,
			'Rand'	 : Math.random()
		};
		$.post( '/', myVars, hg.RemoveItemCallback );
	}else{
		return (false);
	}
}

hg.RemoveItemCallback = function(myReturn){
	window.location.reload();
}

hg.CheckOut = function() {
	if(confirm('Are you sure you want to purchase all of the bling in your basket?')) {
		$('.CartMessage').html('<img src="/images/e1/t1/ajx.load.round.gif" />');
		var myVars = {
			'IDX'	 : 'cart.process',
			'Action' : 'CheckOut',
			'Rand'	 : Math.random()
		};
		$.post( '/', myVars, hg.CheckOutCallback );
	}else{
		return (false);
	}
}

hg.CheckOutCallback = function(myReturn){
	myReturn = myReturn.split( '|' );
	if ( myReturn[0] == 'SUCCESS' ) {
		alert('Thank you! Wanna shake it with your new Bling?');
		window.location.href = ( myReturn[1] != null ) ? '/' + myReturn[1] + '/' :  '/viewprofile/';

	} else if ( myReturn[0] == 'NotEnoughShell') {
		$('.CartMessage').html('');
		if ( confirm ( 'To buy all the Bling currently in your basket, you need more Seashell Points. Click "OK" to buy more Seashell Points, or "Cancel" to remove certain items in your basket.') )
			window.location.href = '/view.item/?ItemID=60 ';
		else
			return (false);
	} else {
		$('.CartMessage').html(myReturn[0]);
	}
}

hg.GetUserItems = function(itemTypeID, page){
	if(arguments[2] != null) {
		if(arguments[2] == 'TypeID') { 
			switch (arguments[4]) {
				case 'One':
				case 'Top':
				case 'Bottom':
				case 'Shoes':
					$('#UserItemList').load('/user.items/?ItemTypeID=' + itemTypeID + '&Page=' + page + '&cid=' + arguments[3] + '&rand=' + Math.random() + '&piece=' + arguments[4]);						
				break;

				default:
					$('#UserItemList').load('/user.items/?ItemTypeID=' + itemTypeID + '&Page=' + page + '&cid=' + arguments[3] + '&rand=' + Math.random());	
				break;
			}
		}else{
			$('#'+arguments[3]).load('/viewprofile.user.items/?ItemTypeID=' + itemTypeID + '&Page=' + page + '&rand=' + Math.random() + '&ViewUserID=' + arguments[2] + '&Type=' + arguments[3] + '&cid=' + arguments[4]);
		}
	}else{
		$('#UserItemList').load('/user.items/?ItemTypeID=' + itemTypeID + '&Page=' + page + '&rand=' + Math.random());	
	}	
}

hg.DisplayItemType = function(theNode, itemTypeID, characterTypeID){
	var parentNode = theNode.parentNode;
	var childNodes = parentNode.childNodes;
	for(i=0; i<childNodes.length; i++){
		if(childNodes[i].tagName == 'A'){
			childNodes[i].className = childNodes[i].className.replace(' ButtonHover', '');
		}
	}
	theNode.className = theNode.className + ' ButtonHover';

	if(itemTypeID == 1 && characterTypeID == 1) {
		$('.ProfileNav').css('display', 'none');
		$('.ProfileSubNav').css('display', 'block');
	}

	if(arguments[3] == null)
		hg.GetUserItems(itemTypeID, 1, 'TypeID', characterTypeID);
	else
		hg.GetUserItems(itemTypeID, 1, 'TypeID', characterTypeID, arguments[3]);
}

hg.GetItems = function(characterTypeID, itemTypeID, page){
	var itemPiece = (arguments[3] == null) ? '' : '&piece=' + arguments[3];
	$('.ItemList').load('/boutique.items/?CharacterTypeID=' + characterTypeID + '&ItemTypeID=' + itemTypeID + '&Page=' + page + '&rand=' + Math.random() + itemPiece);
}

hg.GetLavadrops = function(characterTypeID, itemTypeID, page){
	$('.LavadropsTree').load('/boutique.items/?ItemTypeID=6&Page=' + page + '&rand=' + Math.random());
}

hg.DisplayBoutiqueType = function(theNode,characterTypeID, itemTypeID){
	if(arguments[3] == null) {
		if(itemTypeID == 1)
			$('.SubCategory.Outfit').css('display', 'block');
		else
			$('.SubCategory.Outfit').css('display', 'none');

		hg.GetItems(characterTypeID, itemTypeID, 1);
	}else{
		hg.GetItems(characterTypeID, itemTypeID, 1, arguments[3]);
	}
	
	$('.Control a').removeClass('Hover');

	$(theNode).addClass('Hover');

}

hg.ToggleEditField = function(theInput, field){
	$('.XHMessage').html('');

	if(theInput.className == 'EditButton SaveState'){
		// Update
		hg.updateProfile(field);
	}else{
		if(field == 'Password') {
			$('.PasswordInputs').css('display', 'inline');
		}else{
			$('#'+field+'Input').css('display', 'inline');
			$('#'+field+'Disp').css('display', 'none');
		}
		theInput.title = 'Save';
		theInput.innerHTML = '<span>Save</span>';
		theInput.className = 'EditButton SaveState';
	}
}

hg.updateProfile = function(theField){
	if(theField == 'Password'){
		$.post('/', {
				'IDX'	: 'profile_update.process',
				'op'	: $('#PasswordInput').val(),
				'np'	: $('#PasswordNewInput').val(),
				'cp'	: $('#PasswordConfirmInput').val(),
				'Rand'	: Math.random()
			}, 
			function(data) {
				data = data.split('|');
				if(data[0] == 'Success') {
					$('#PasswordEdit').attr({'class' : 'EditButton', 'title' : 'Edit'});
					$('#PasswordEdit').html('<span>Edit</span>');
					$('.PasswordInputs').css('display', 'none');
				}

				$('#PasswordInput').val('');
				$('#PasswordNewInput').val('');
				$('#PasswordConfirmInput').val('');

				$('.XHMessage').html(data[1]);
			}
		);

		return(false);
	}
	
	if(theField == 'Sign' || theField == 'Character'){
		var theValue = dom.$(theField+'Input').options[dom.$(theField+'Input').selectedIndex].value;
		theField += 'ID';
	}else if(theField == 'Avatar' && arguments[1] != null){
		theValue = arguments[1];
	}else{
		var theValue = dom.$(theField+'Input').value;
	}
	var myVars	= { 
		'IDX'		: 'profile_update.process',
		'Field'		: theField,
		'Value'		: theValue,
		'Rand'		: Math.random()
	};

	xh.postResponse( '/', myVars, 'hg.updateProfileCallback' );
	return (false);
}

hg.updateProfileCallback = function(myReturn) {
	myReturn = myReturn.split('|');

	if(myReturn[0] == 'Updated') {
		if(myReturn[1] == 'Sign' || myReturn[1] == 'Character') {
			dom.$(myReturn[1]+'Disp').innerHTML = dom.$(myReturn[1]+'Input').options[dom.$(myReturn[1]+'Input').selectedIndex].innerHTML;

		} else if(myReturn[1] == 'Avatar') {
			window.location.reload();
			return(true);
		} else {
			var x = (dom.$(myReturn[1]+'Input').value.length > 50) ? dom.$(myReturn[1]+'Input').value.substr(0, 45) + '...' : dom.$(myReturn[1]+'Input').value;
			dom.$(myReturn[1]+'Disp').innerHTML = x;

		}

		dom.$(myReturn[1]+'Disp').style.display = 'block';
		dom.$(myReturn[1]+'Edit').className = 'EditButton';
		dom.$(myReturn[1]+'Edit').title = 'Edit';
		dom.$(myReturn[1]+'Edit').innerHTML = '<span>Edit</span>';
		dom.$(myReturn[1]+'Input').style.display = 'none';
	}else{
		alert(myReturn[0]);
	}
}

function TurnSound(state){
	if(state == 'On')
		pre.SiteProxy.call('TurnSoundOn');
	else if(state == 'Off')
		pre.SiteProxy.call('TurnSoundOff');
}

function CheckLogin(URL){
	var myVars = {
		'IDX' : 'check.login.process',
		'URL' : URL,
		'Rand': Math.random()
	};
	xh.postResponse( '/', myVars, 'checklogincallback' );
}

function checklogincallback(myReturn){
	myReturn = myReturn.split('|');
	if(myReturn[0] == 1){
		location.href=myReturn[1];	
	}else{
		location.href='/login/?RedirectURL=downloads.icons';
	}
}

function hideAll() {
	var elements = dom.$c(document.body, 'CS');
	for(i = 0; i < elements.length; i++) {
		elements[i].style.display = 'none';
	}
}

var trim = function(strIn){
	return strIn.replace(/(^\s*)|(\s*$)/g, "");
}

// Characters Left
function MaxChar(theInput, maxLength) {
	 document.getElementById('CharLeft').innerHTML = '';
	 if(theInput.value.length >= maxLength) {
		theInput.value = theInput.value.substring(0, maxLength);
		document.getElementById('CharLeft').innerHTML = '<font color="red">0</font>';	
		return;
	}
	document.getElementById('CharLeft').innerHTML = maxLength - theInput.value.length;
}

function getInfo(myEvent, info) {
	if(info.length < 50)
		return;

	Cursor = new vpi.Cursor(myEvent);
	document.getElementById('MoreInfo').style.display = "block";
	document.getElementById('MoreInfo').style.top	= (Cursor._y - 220) + 'px';
	document.getElementById('MoreInfo').style.left	= (Cursor._x + 5) + 'px';
	document.getElementById('MoreInfo').innerHTML	= info;
}

function hideInfo() {
	document.getElementById('MoreInfo').style.display = "none";
}

// on document ready state
$(document).ready(function(){
	// this initialises the demo scollpanes on the page.
	$('.ScrollContent').jScrollPane({showArrows:true, scrollbarWidth: 10, arrowSize: 10});
});

function AvatarScroll(Direction) {
	if(Direction == "Next") {
		if(CurrentAvatar == AvatarArray.length-1) {
			document.getElementById('ShowAvatar').style.backgroundImage="url('" + AvatarArray[0] + "')";
			CurrentAvatar=0;
		} else {
			document.getElementById('ShowAvatar').style.backgroundImage="url('" + AvatarArray[CurrentAvatar+1] + "')";
			CurrentAvatar++;
		}
	} else {
		if(CurrentAvatar == 0) {
			document.getElementById('ShowAvatar').style.backgroundImage="url('" + AvatarArray[AvatarArray.length-1] + "')";	
			CurrentAvatar=AvatarArray.length-1;
		} else {
			document.getElementById('ShowAvatar').style.backgroundImage="url('" + AvatarArray[CurrentAvatar-1] + "')";
			CurrentAvatar--;
		}
	}
}

function changeBG(backgroundID) {
	$('.GlitzyRightCol').css('background', 'url(\'/img/e1/t1/sa.glitzyprofile.wp' + backgroundID + 'big.gif\')');
	for(thumbID=1; thumbID<11; thumbID++) {
		$('#Thumb' + thumbID).css('color', '#7D1C66');
		$('#Thumb' + thumbID + ' img').css('border-color', '#FFFFFF');
	}
	
	$('#Thumb' + backgroundID).css('color', '#FFF000');
	$('#Thumb' + backgroundID + ' img').css('border-color', '#FFF000');
	
	$('#CurrentWallpaper').val(backgroundID);
}

function addWallpaperToCart() {
	if($('#CurrentWallpaper').val() > 0) {

		$.post('/', {
				'IDX'				: 'cart.process',
				'Action'			: 'AddWallpaperToCart',
				'WallpaperID'		: $('#CurrentWallpaper').val(),
				'Rand'				: Math.random()
			}, function(data) {
				$('.CartMessage').html(data);
		});
	} else {
		$('.CartMessage').html(data) = 'Please select a wallpaper.';
	}
}

hg.openSurfTip = function ()  {
	$('body').append('<div class="SurfTip" id="SurfTip">hi</div>');
	$('.SurfTip').css({'left' : hg.windowLeft});
	$(':input[@class="SurfTipHide"]').css('display', 'none');
	surfTip.write('SurfTip');
}

hg.closeSurfTip = function() {
	$('.SurfTip').remove();
	$(':input').css('display', 'inline');
}

hg.doodleHover = function(parentNode) {
	$(parentNode).append('<div class="VP_Post4Shell"></div>'); 
}

hg.bannerClose = function() {
	var SectionID = jQuery( this ).attr( 'rel' );
	document.cookie = 'HGBannerClose['+ SectionID +']=closed; expires=0; path=/';
	jQuery( this ).parents( '.sys-bannerWrapper' ).remove();

	return false;
}

function updateDuration() {
	$.post('/duration.process/');
}
 // Event Delegation ------------------------------------[TN] 
 jQuery.delegate = function(Rules) { 
      return function(e) { 
           var Target = $(e.target); 
           for (var Selector in Rules) 
                if (Target.is(Selector)) return Rules[Selector].apply(this, $.makeArray(arguments)); 
      } 
 } 
 //------------------------------------------------------[TN]
//-----------------------------------------------------------

jQuery( document ).ready( function() {
	jQuery( '.sys-banner-close' ).click( hg.bannerClose );
} );