var required_fields = {
	user:        			 new Array("user"),
	tag:               new Array("tags"),
	playlist:          new Array("playlists"),
	featured:          false,
	recently_uploaded: false,
	favorited:         false,
	discussed:         false,
	password:					 false
};

// Global variable
var hashPlaylistSelected = false;

$(document).ready(function() {
	if ($('#widget_type').val()) {
		var widget_type = $('#widget_type').val();
		$(".widgetChooser li.current").removeClass('current');
		$("#" + widget_type).addClass('current');
	}

	setup_form();
	
	// Check hash
	
	if (location.hash.match(/playlist-[0-9]+/)) {
		var num = location.hash.replace(/[^0-9]/g, '');
		$('select#source [value=playlist]').attr('selected', 'selected');
		setup_form();
	}

	$('.widgetChooser li a').click(function(e) { // Changed by Andrew
		e.preventDefault();
		var current = $(this).parent();
		if (! $.browser.msie) { // The fade effect doesn't look good in IE browsers
			$('#widgetForm').fadeOut(function(){
				$('.widgetChooser li.current').removeClass('current');
				current.addClass('current');
				$('#widgetForm').fadeIn();
				setup_form();
				refresh_preview();
			});
		} else {
			$('.widgetChooser li.current').removeClass('current');
			current.addClass('current');
			setup_form();
			refresh_preview();
		}
	});

	$("form#theform input, form#theform select").change(function() {
		if ($(this).attr('id') == 'user') {
			required_fields.password = false;
			$('#password').val('');
		}
		setup_form();
		refresh_preview();
	});

	$("form#theform").submit(function(e) {
		e.preventDefault();
		setup_form();
		refresh_preview();
	});

	$("#update_link").click(function(e) {
		e.preventDefault();
		refresh_preview(true);
	});

	$("input.colorpicker").each(function() {
		var picker = $(document.createElement("div")).addClass("colorpicker").css("display", "none"); // Modified by Andrew - using css() instead of hide() for Safari
		$(this).after(picker);
		addClearLink($(this));
		$.farbtastic(picker).linkTo($(this));
	});

	// Begin Andrew's changes
	
	$("input.colorpicker").focus(function() {
		// Hide currently shown stuff
		$(".openColorpicker div.colorpicker").hide();
		$(this).parents(".openColorpicker").removeClass("openColorpicker");
		// Show the desired colorpicker
		$(this).siblings("div.colorpicker").show();
		$(this).parents(".form-item").addClass("openColorpicker");
	});
	
	$("body").click(function(e){
		if ($(e.target).parents('.colorpicker, .openColorpicker').length == 0 && $('.openColorpicker').length > 0) { // Use $(e.target) instead of $(this)!
			$("div.colorpicker").fadeOut("fast", function(){
				$(this).parents(".openColorpicker").removeClass("openColorpicker");
			});
			addClearLink($(this));
			refresh_preview();
		}
	});
			
	$("#advanced_skinning").click(function() { // Before I added this, clicking the #advanced_skinning checkbox would not make the other forms show in IE6 and IE7
		setup_form();
	})
	
	// End Andrew's changes
	
	$("#code").click(function(){
	   	$(this).select();
	});

	$("#playlist_login_home input[type=submit]").click(function(e) {
		e.preventDefault();
		
		// Remove error messages momentarily
		$(this).parent().find('.form-error').remove()
		    
		// Make sure there is something in the username and password fields
		if ($('#login_user').val() == '' || $('#login_pass').val() == '') {
			$(this).after('<p class="form-error">Please enter a username and a password</p>')
			return;
		}
		
		$.post("/login.php?ajax=true", {user: $("#login_user").val(), password: $("#login_pass").val()}, function(data) {
			if(data.error) {
				$(e.target).after('<p class="form-error">Invalid username or password</p>');
			} else {
				loadPlaylists();
				current_user = data.user;
			}
		}, 'json');
	});

	if(check_required_fields) refresh_preview();
});

function addClearLink(el) {
	// Make the "clear" link only if one doesn't exist already
	if (el.siblings(".colorpickerClear").length == 0 && el.val().length > 0) {
		var clearlink = $(document.createElement("a")).addClass("colorpickerClear").attr('href','#').text("clear").click(colorpickerClear);
		el.after(clearlink);
	}
}

function colorpickerClear(e) {	
	e.preventDefault();
	$.farbtastic($(this).siblings("div.colorpicker")).setColor("#000000"); // Reset colorpicker
	$(this).siblings("input.colorpicker").val("").css('background','white'); // Clear input field
	$(this).remove();
}

function setup_form() {
	var widget_type = $('.widgetChooser li.current').attr('id');
	$('#widget_type').val(widget_type);
		
	$('form#theform .option, form#theform .width_option').hide();
	
	var fields = new Array();
		
	switch(widget_type) {
		case 'reel':
			$("#user, #autoplay, #reel_width").parent().parent().show();
			if (required_fields.password) $('#password').parent().parent().show();
			return;
			break;
		case 'js_list':
			fields.push("#style", "#show_player", "#list_width");
			if($('#style').val() == 'grid') fields.push("#videos_per_row", "#show_titles");
			if($('#style').val() == 'list') fields.push("#list_location", "#show_descriptions");
			if($('#show_player').attr('checked')) {
				fields.push('#autoplay', '#player_type');
				if($('#player_type').val() == 'simple') fields.push('#skin_color', '#advanced_skinning');
				if($('#advanced_skinning').attr('checked')) {
					fields.push('#inactive_color', '#active_color', '#hover_color', '#bar_color');
				}
			}
			break;
		case 'playlist':
			fields.push("#title", "#autoplay", "#skin_color", "#advanced_skinning", "#playlist_width");
			if($('#advanced_skinning').attr('checked')) {
				fields.push("#inactive_color", "#active_color", "#hover_color", "#bar_color");
			}
			break;
	}
	
	fields.push("#source");
	
	if($('#source').val() != 'playlist') fields.push("#max");
	
	switch($('#source').val()) {
		case 'user':
			fields.push("#user", "#tags", "#sort");
			if (required_fields.password) fields.push('#password');
			$("#tag_optional").show();
			break;
		case 'tag':
			fields.push("#tags", "#sort");
			$("#tag_optional").hide();
			break;
		case 'playlist':
		  fields.push("#playlists");
		  break;
		case 'discussed':
		case 'popular':
		case 'discussed':
			fields.push("#time_period");
			break;
	}
	
	var selector = fields.join(',');
	
	$(selector).parent().parent().show(); // Kyle, this is so clever that I don't think I can talk to you anymore :)
	$('#widget_width').val($('.width_option:visible input').val());
	
	if(current_user) {
	  $("#playlist_login_home").hide();
	  $("#playlists").show();
      $("#playlists-link").show();
	  
	  if($("#playlists option").length == 0) {
	    $("#playlists").hide();
	    $("#no-playlists").show();
	    $("#playlists-link").hide();
	  } else {
	  	
	  	if (! hashPlaylistSelected && location.hash.match(/playlist-[0-9]+/)) {
		  	// Select playlist from hash
		  	var num = location.hash.replace(/[^0-9]/g, '');
		  	var option = $('#playlists [value='+num+']');
		  	
		  	
		  	if (option.length > 0) {
		  		option.attr('selected', 'selected');
		  	}
		  	
		  	hashPlaylistSelected = true;
	  	}
	  }
	} else {
	  $("#playlist_login_home").show();
	  $("#playlists").hide();
	  $("#playlists-link").hide();
	}
}

var last_update = false;

function refresh_preview(force) {
	var msg = $('#widgetPreviewPrompt');
	
	if (msg.data('old_text')) {
		msg.text(msg.data('old_text'));
		msg.removeData('old_text');
	}
	
	if(arguments.length == 0) {
		force = false;
	}
	
	if(!check_required_fields()) return;
	
	$('#widget_width').val($('.width_option:visible input').val());
	
	var elements = $(".option:visible input[type!=checkbox], .option:visible input[type=checkbox]:checked, .option:visible select, #widget_type, #widget_width");
	
	$("#updating_text").show();
	$("#update_link").hide();
	$("#code").val('');
	
  $.ajax({
    type: "POST",
    url: "code/index.php",
    dataType: "json",
    data: elements,
		error: function() {
			$("#updating_text").hide();
			$("#update_link").show();
		},
    success: function(data){
			$("#updating_text").hide();
			$("#update_link").show();
			
			if (data.error) {
				if (data.user_is_hidden) {
					required_fields.password = true;
					
					if (data.login_error) {
						$('#login_error').show();
					} else {
						$('#login_error').hide();
					}
				} else {
				  required_fields.password = false;
				}
				if (data.no_videos) {
					msg.data('old_text', msg.text());
					msg.text('No videos found! To create a Vidget, upload some videos and try again.');
				}
				
				setup_form();
			} else {
				$('#login_error').hide();
				
				if(data.css) {
					full = data.css + data.template;
					$("head").append(data.css);
				} else {
					full = data.template;
				}
	      $("#preview_pane").html(data.template);
	      $("#code").val(full);
			}
    }
  });
}

function check_required_fields() {
	var type = $("#source").val();
	var fields = required_fields[type];
	
	if(!fields) return true;
	
	for(i=0;i<fields.length;i++) {
		if(jQuery.trim($("#" + fields[i]).val()) == '') {
			// required field is blank
			return false;
		}
	}
	
	return true;
}

function loadPlaylists() {
  $.get('/playlists/callback.php', {method: 'viddler.playlists.getByUser'}, function(data) {
    buildPlaylistSelect(data.playlists);
    setup_form();
    refresh_preview();
  },'json');
}

function buildPlaylistSelect(playlists) {
  if(arguments.length == 0) {
		playlists = false;
	}
  
  var el = $("#playlists")
  el.empty();
  
  $("#no-playlists").hide();
  for(i=0;i<playlists.length;i++) {
    if(playlists[i].video_count > 0) {
      var op = $('<option value="' + playlists[i].id + '">' + playlists[i].name + ' (' + playlists[i].video_count + ' videos)</option>');
      el.append(op);
    }
  }
  
  setup_form();
}
