function replaceSubmitButton(wrapper, cssClass)
{
	var submitBtn = wrapper.find('input:submit');
	var submitLink = jQuery('<a href="#" class="' + cssClass + '"><span>' + submitBtn.val() + '</span></a>');
	submitBtn.replaceWith(submitLink);
	submitLink
		.click(function()
				{
					var form = jQuery(this).parents('form');
					form.submit();
					return false;
				})
}

function replaceSubmitButtons()
{
	replaceSubmitButton(jQuery('form').not('.HeaderSignInForm'), 'lnkArrowBtn');
	replaceSubmitButton(jQuery('form.HeaderSignInForm'), 'btnLogin');
}

function initColorPickers()
{
	var colorPickerFields = jQuery('input.hasColorPicker');
	/* color picker */
	var colorPicker = jQuery('<div id="picker"></div>').appendTo('body');
	
	colorPicker = colorPicker.extend({
					on: function()
							{
								var cp = jQuery(this);
								cp.css({'display': 'block'});
							},
					off: function()
							{
								var cp = jQuery(this);
								cp.css({'display': 'none'});
							},
					setPosition: function(x, y)
									{
										var cp = jQuery(this);
										cp.css({
													'left': x + 'px',
													'top': y + 'px'
												})
									}
					},
					colorPicker);
	
	// init farbtastic picker
	var f = $.farbtastic(colorPicker);
	
	// add popup close button
	jQuery('<a href="#" class="popupCloseBtn" title="Close color picker popup">[X]</a>')
			.appendTo(colorPicker)
			.click(function(){colorPicker.off();return false;});
			
	colorPickerFields
	  .each(function() // add picker popup trigger
			{
				f.linkTo(this);
				var inputElement = jQuery(this);
				var colorWheelTrigger = jQuery('<a href="#" class="pickerPopupTrigger" title="Click to select color">[...]</a>')
								.click(function(){inputElement.focus(); return false;}); // set focus on input element, which triggers the popup
				inputElement.after(colorWheelTrigger);
			})
	  .focus(function() // display picker popup on focus
			{
				f.linkTo(this);
				var inputElement = jQuery(this);
				var linkElement = inputElement.next();
				colorPicker.setPosition(linkElement.offset().left + linkElement.width()/2, linkElement.offset().top + linkElement.height()/2);
				colorPicker.on();
			});
	
	// elements that close the picker popup on focus ...
	jQuery('input, select, textarea').not(colorPickerFields)
		.focus(function(){colorPicker.off()});	
}

function initCodeCopy()
{
	var bpTriggers = jQuery('a.lnkBtnCopyCode');
	bpTriggers
		.click(function()
			{
				var t = jQuery(this);
				var tt = jQuery(t.attr('href'));
				tt.select();
				return false;
			})
		.each(function()
			{
				var t = jQuery(this);
				var tt = jQuery(t.attr('href'));
				tt.click(function(){
							var ta = jQuery(this);
							ta.select();
						});
			})
}

function addInterfaceElements()
{
	var mainNav = jQuery('#MainNav');
	if(mainNav.size() > 0)
	{
		jQuery('#MainWrapper').append('<div class="MainWrapperTopRight"></div>');
	}
}

function setFieldEditEvents()
{
	var fieldsFilter = jQuery('input, textarea, select');
	fieldsFilter
		.change(function()
			{
				var f = jQuery(this);
				fieldChanged(f.attr('name'), f.val());				
				return false;
			})
}

function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}

function fileUploadedLogo(u) {
	jQuery('input[name=LogoURL]').val(u);
	fieldChanged("LogoURL", u);
	adjustClearImageLinks();
}

function fileUploadedBackground(u) {
	jQuery('input[name=BackgroundPhotoURL]').val(u);
	fieldChanged("BackgroundPhotoURL", u);
	adjustClearImageLinks();
}

function fieldChanged(fieldName, fieldValue)
{
	if (getFlashMovie("WidgetFla") != undefined) {
		var res = new String(fieldValue);
		if (fieldName.indexOf("Color") != -1) {
			res = res.replace('#', '0x');
		}
		
		if ((fieldName == 'BackgroundPhotoURL') || (fieldName == 'LogoURL') || (fieldName == 'Goal') || (fieldName == 'Currency')) res = res + "";
		if ((fieldName == 'Amount_1') || (fieldName == 'Amount_2') || (fieldName == 'Amount_3') || (fieldName == 'Amount_4') || (fieldName == 'Amount_5') || (fieldName == 'Amount_6')) res = res + "";


		try{console.log("Sending to FLA " + fieldName + ' > |' + res + '|');}catch(err){}//
		getFlashMovie("WidgetFla").sendToActionscript(fieldName, res);
	}
//	try{console.log(fieldName + ' > ' + fieldValue);}catch(err){}//
}

function layoutResized()
{
	var bodyWidth = parseInt(jQuery('body').width());
//	if(bodyWidth >= 1150) // sn nav displayed in center
		jQuery('#SNNav').attr('style', ''); // clear previous inline style, back to the original css styles
//	else // there is no room for all top bar elements, sn nav moved to top right
//		jQuery('#SNNav')
//			.css({
//			     	top: '60px',
//				right: '50%', 
//			     	left: 'auto', 
//				marginLeft: '0px',
//				marginRight: '-424px'
//			});
}

function my_twitter_at(value) {
	var res = new String(jQuery.trim(value));
	
	if(res == '') return '';

	res = res.replace("twitter.com", "");
	res = res.replace("www.", "");
	res = res.replace("http://", "");
	res = res.replace("https://", "");
	res = res.replace("/", "");

	return '@' + res;
}


function setTwitterFieldEvents()
{
	var twT = jQuery('#TwitterName');
	if(twT.size() >0)
	{
		twT.change(function()
				{
					var twT = jQuery(this);
					var twName = my_twitter_at(twT.val());
					if(twName != '')
					{
						var twTT = jQuery('#TwitterShareMessage');
						if(twTT.size() >0)
						{
							var twTTMessage = new String(twTT.text());
							twTTMessage = twTTMessage.replace('join @WhatGives', 'join ' + twName + ' and @WhatGives');
							twTTMessage = twTTMessage.replace('Join @WhatGives', 'Join ' + twName + ' and @WhatGives');
							twTT.text(twTTMessage);
						}
					}
				})
	}
}

function adjustClearImageLinks() {
	var defaultBackgroundHint = jQuery('#defaultBackgroundHint');
	var removeBackgroundHint = jQuery('#removeBackgroundHint');
	
	var backgroundValue = jQuery('input[name=BackgroundPhotoURL]').val();
	if (backgroundValue != '') {
		defaultBackgroundHint.css('display', 'none');
		removeBackgroundHint.css('display', 'block');
	} else {
		removeBackgroundHint.css('display', 'none');
		defaultBackgroundHint.css('display', 'block');	
	}

	var defaultLogoHint = jQuery('#defaultLogoHint');
	var removeLogoHint = jQuery('#removeLogoHint');
	
	var logoValue = jQuery('input[name=LogoURL]').val();
	if (logoValue != '') {
		defaultLogoHint.css('display', 'none');
		removeLogoHint.css('display', 'block');
	} else {
		removeLogoHint.css('display', 'none');
		defaultLogoHint.css('display', 'block');	
	}
	
	var removeLogoLink = jQuery('#removeLogoHint a');
	removeLogoLink.click(function()
				{
					fileUploadedLogo("");
					return false;
				});

	var removeBackgroundLink = jQuery('#removeBackgroundHint a');
	removeBackgroundLink.click(function()
				{
					fileUploadedBackground("");
					return false;
				});

}

jQuery(function(){
	replaceSubmitButtons();
	initColorPickers();
	initCodeCopy();
	addInterfaceElements();
	setFieldEditEvents();
	setTwitterFieldEvents();
	layoutResized();
	adjustClearImageLinks();

	jQuery("#scrollingText").smoothDivScroll({autoScroll: "always", autoScrollDirection: "endlessloop", pauseAutoScroll: "mouseover", scrollingSpeed: 6});

})

jQuery(window).resize(function(){layoutResized()})
