/*
	main application javascript functions
	this must be loaded AFTER jquery to use $functions

	this application.js file is included on ALL pages so only global
	functionality in here, please.

*/


function widget_window_popups() {
	/* Opens widgets in a lightbox. */
	$widgets = $(".widget-edit-button")
	var reload_func = function() { window.location.reload(); };

//	$widgets.lightbox({
//			'width': 800,
//			'iframe':true,
//			'autoresize': true,
//			'containerResizeSpeed': 50
//		}, reload_func);

	$widgets.prettyPhoto({
		default_width:800,
		callback: reload_func,
		allow_resize: false,
		deeplinking: false,
		social_tools:""
	})

}

function draggable_widgets() {

}

function sortable_widgets() {

}

function apply_type_classes() {
	/* add class to inputs */
	$('input').each(function() {
	    $(this).addClass(this.type);
	});
}



function ajax_removal_of_widgets() {

}

function highlight_broken_functionality() {
	$('.not-working').live('click', function(ev) {
		return confirm("This feature is still in development. Continue?");
	});
}

/* maximize div */
function minimisers() {
	$(".maximiseBut").live('click', function(){
		$("div.minimise").animate({
			height: "100%"
		})
		.animate({
			height: "120%"
		}, "fast");
		$(".maximiseBut").toggle();
		$(".maximiseBut").attr("href", "#");
	});

   $(".minimiseBut").live('click', function(){
		$("div#minimise").animate({
			height: "0px"
		}, "fast");
   });
}

function elastic_widgets() {
	/*
		Allows widgets that collapse and expand it's content.
		Requires widgets to be enclosed with a .elastic class and it's second
		child (.content typically) to be the element to be toggled open/closed.
	*/
	// css should already be doing this, but this doesn't hurt
	$(".elastic.default-closed > .content").hide();
	$(".elastic > .widgetHeader").live("click", function() {
		//$(this).children().eq(1).fadeToggle();
		$(this).next().slideToggle(150);
		$(this).toggleClass("toggle");
	});
}


function smart_youtube_resizer() {
	/*
		Pretty simple: the width of the player is the widget of it's parent
		.content container and it's height is half of that.

		Rule applies to all youtube
	*/
	$(document).find(".youtube-player").each(function() {
		var container = $(this).parents(".content");
		var new_width = container.width();
		var new_height = new_width / 2;
		$(this).width(new_width);
		$(this).height(new_height);
	});
}

function add_iframe_popups() {
	/*
		Attaches an iframe lightbox to anything with the .lightbox-iframe class.
		Useful for flooding people's brains with endorphins.
	*/
	var args = {
		'height': '75p',
		'width': 800,
		'iframe': true,
		'autoresize': true
	}
	var reloading_iframe_popups = $(".reloading-ajax-iframe")
	var iframe_popups = $(".ajax-iframe")
	//.lightbox(args);

//	var reload_func = function() { window.location.reload(true); };
//	reloading_iframe_popups.lightbox(args, reload_func)
}


function mark_markable_containers() {
	/*
		For all containers that are marked as markable

	*/
	$(".markable").each(function() {
		$(this).click(function() {
			$(".markable").removeClass("marked");
			$(this).toggleClass("marked");
		});
	});
}

function csrfify_requests() {
	$('html').ajaxSend(function(event, xhr, settings) {
		function getCookie(name) {
		    var cookieValue = null;
		    if (document.cookie && document.cookie != '') {
		        var cookies = document.cookie.split(';');
		        for (var i = 0; i < cookies.length; i++) {
		            var cookie = jQuery.trim(cookies[i]);
		            // Does this cookie string begin with the name we want?
		            if (cookie.substring(0, name.length + 1) == (name + '=')) {
		                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
		                break;
		            }
		        }
		    }
		    return cookieValue;
		}
		if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
		    // Only send the token to relative URLs i.e. locally.
		    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
		}
	});
}

String.prototype.bool = function(){
	switch(this.toLowerCase()){
		case "true": case "yes": case "1": return true;
		case "false": case "no": case "0": case null: return false;
		default: return Boolean(this);
	}
}
Number.prototype.bool = function(){
	switch(this){
		case 1: return true;
		case 0: case null: return false;
		default: return Boolean(this);
	}
}

var Application = {


	checkboxen: function(){
		if(jQuery && $['checkBoxSlider'] ){
			var formItems = $(".form .boolean-slider-toggle")
			var labelOn = "On"
			var labelOff = "Off"
			var resetButton = $(".form input[type='reset']")
			resetButton.unbind()
			resetButton.click(function(){
				$this = $(this)
				this.form.reset()
				formItems.each(function(index, item){
					$this = $(this)
					var $sliderCheckboxWidget = $this.data("slider-checkbox-widget")
					var $current = $(item).attr("checked")
					var $default = $(item).data("default")
					var $changed = ($current && $current != $default )

					if ($changed){
						$.log( $(item), "default",$default, "value", $current , "hasChanged", $changed)
						$this.trigger('mousedown')
					}
				})
			})

			formItems.each(function(index,formItem){
				$formItem = $(formItem)
				if( $formItem.attr("data-touchscreen-widget") == 'checkbox-slider') return false;

				var onAttr = $formItem.attr("data-label-on")
				var offAttr = $formItem.attr("data-label-off")

				var thisLabelOn = onAttr?onAttr:labelOn
				var thisLabelOff = offAttr?offAttr:labelOff

				$formItem.data("default", $formItem.attr('checked') )

				$formItem.checkBoxSlider({
					uncheckedLabel: thisLabelOff,
					checkedLabel: thisLabelOn,
				})

				$formItem.attr("data-touchscreen-widget", 'checkbox-slider')
			})

		}
	},

	tooltips: function(){

		var TipTipDefaults = {
			maxWidth: "256px",
			edgeOffset: 10
		}

		$(".form").find(".field-help").each(function(){
			$this = $(this)
			if(($this.find(".inner").text()).length > 0 ){
				targetElementSelector = $this.parent().find(".field-label label").attr("for")
				$this.parent()
					.tipTip($.extend({}, {
						defaultPosition: "right",
						content: $this.html()
					}, TipTipDefaults ))
					.hover(function(){
						$(this).toggleClass("hover")
					},function(){
						$(this).toggleClass("hover")
					})
			}
			$this.hide()
		})

		$(".tooltip").each(function(index, item){
			var $this = $(item);
			var tooltip_content = $this.attr('title')

			if($this.attr('data-tooltip-selector')){
				tooltip_content = $this.find( $this.attr('data-tooltip-selector') )
				tooltip_content.hide()
				tooltip_content = tooltip_content.html()
			}
			keepalive = false
			if($this.attr('data-tooltip-keepalive')){
				keepalive = $this.find( $this.attr('data-tooltip-keepalive') )
			}

			$this.tipTip($.extend( {
				content: tooltip_content,
				keepAlive: keepalive,
				defaultPosition: $this.attr("data-tooltip-position")
			}, TipTipDefaults))

		})

	},

	searchFormFieldEffects : function(){
    $("#query, #location").fieldBlurSwitch();
    $("#loopedSlider").loopedSlider({
        autoStart: 0,
        slidespeed: 1000,
        autoHeight: true
    });
	},

	registrationPanelToggle: function(){

    var registrationPanelSelector = "#quickRegistrationPanel";
    var registrationPanel = $(registrationPanelSelector)
        registrationPanel.data("closedHeight", 0 )
        registrationPanel.data("openHeight", 240 )
        registrationPanel.data("isOpen", false);

    var toggleButtonSelector = ".session-bar .sign-up";
    var toggleButton = $(toggleButtonSelector)

    toggleButton.click(function(){
      $this = $(this);
      $target = registrationPanel;

      isOpen = $target.data("isOpen")

      if (isOpen){
        targetHeight = $target.data("closedHeight")
      }else{
        targetHeight = $target.data("openHeight")
      }
      $target.data("isOpen", !isOpen )

      $target.animate({
          height:  targetHeight
        }, 1500, 'easeOutExpo');

      return false;
    })

	},

	colourPicker: function(){

    $colourPicker = $("<div>")
      .attr("id", "colourPicker")
      .css({
        position: 'absolute',
        top: 0,
        left: 0,
        backgroundColor: "#222",
        borderRadius: ".4em",
        boxShadow: "0 5px 5px #000",
        zIndex:999
      })
      .appendTo("body")
      .hide();

    $("#colourPicker").farbtastic("#id_background_colour")

    $("#id_background_colour").click(function(){
      $this = $(this)
      //The Middle
      targetY = $this.offset().left - $colourPicker.outerWidth()
      // Below the field
      targetX = $this.offset().top
      $colourPicker
        .css({
          top: targetX,
          left: targetY
        })
        .slideDown()
    }).blur(function(){
      $colourPicker.slideUp()
    })


	}

}
/* bootstrap */

$(document).ready(function(){

	csrfify_requests();

	apply_type_classes();
	minimisers();
	highlight_broken_functionality();

//	ajax_removal_of_widgets();
//	draggable_widgets();
//	sortable_widgets();

//	elastic_widgets();
	smart_youtube_resizer();


	widget_window_popups();
	add_iframe_popups();

	mark_markable_containers();

	Application.searchFormFieldEffects()
	//Application.registrationPanelToggle()



});


