/* Copyright (c) 2010 AZPixels, LLC */

/*****************************************
*   Common Javascript                    *
******************************************/

/*** Ajax Defaults **********************/

;(function($){

	// Default AJAX attributes
	$.ajaxSetup({
		cache: false,
		type: 'POST',
		dataType: 'json'
	});

	// Set Error Handler
	$(window).ajaxError( function (event, XMLHttpRequest, ajaxOptions, thrownError) {
		//$.notice("AJAX Connection Error", "notice-error", true);
	});
	
	// I dont like this, change it later when we redo all this
	$(window).ajaxSuccess(  function (event, XMLHttpRequest, ajaxOptions) {
		// If JSON
		if (ajaxOptions.dataType == 'json') {

			// Check to see if we have JSON processing capacity
			if (typeof $.parseJSON != 'undefined') {
				var response = $.parseJSON(XMLHttpRequest.responseText);
			} else {
				eval('var response = ' + XMLHttpRequest.responseText + ';');
			}
			
			// If there is an error
			if (typeof response.error != 'undefined' && response.error) {
			
				// There is an error, post notice
				if (typeof response.error_message !== "undefined") {
					$.notice(response.error_message, 'notice-error');
				}
				
			// If the response came with a notice
			} else if (typeof response.notice != 'undefined') {
				$.notice(response.notice, 'notice-info', true);
			}
			
		}
	});
	
})(jQuery);


/*** Display Notice *********************/

// Backwards compatibility
function display_notice(notice_message, notice_type, fadeout) {
	$.notice(notice_message, notice_type, fadeout);
}

// More backwords campatibility
// The new way of handling AJAX uses global ajax events to handle notices, making it uneccisary to call these functions.
// To turn off the global ajax handlers, set global: false in the ajax options.
function ajax_notice(){}
function ajax_error(){}

/*****************************************
*   Common Utility Plugins               *
******************************************/

/*** Watch State ************************/
;(function($){$.fn.watch_state=function(n,on,off,i){var r=this;this.each(function(){var $e=$(this);if(typeof on=="undefined"&&typeof off=="undefined"){r=$e.data(n);return;}else{if(typeof on!="undefined"){$e.bind(on,function(){$e.data(n,true);});}if(typeof off!="undefined"){$e.bind(off,function(){$e.data(n,false);});}if(typeof i!="undefined"){$e.data(n,i);}}});return r;}})(jQuery);

/*** Templates **************************/
;(function($){$.fn.fill_template=function(d){this.each(function(){var t=$(this);if(typeof d.method=='undefined'||d.method=='html'){t.find(d.name).html(d.value);}else if(d.method=='text'){t.find(d.name).text(d.value);}else if(d.method=='val'){t.find(d.name).val(d.value);}else if(d.method=='attr'){t.find(d.name).attr(d.value.name,d.value.value);}});return this;}})(jQuery);

/*** Notice ******************************/
;(function($){$.notice=function(notice_message,notice_type,fadeout){if(typeof notice_message==='string'&&notice_message.length>0){var notice_div=$('#notice');if(notice_div.length>0){var parts=notice_message.split("\r\n");var notice_messages="";$.each(parts,function(i){if(parts[i].length>0){notice_messages+="<span>"+parts[i]+"</span>";}});notice_div.empty().append($('<p>'+notice_messages+'</p>')).removeClass().addClass('notice').addClass(notice_type).fadeIn(500);if(fadeout){setTimeout(function(){notice_div.fadeOut(1000)},3000);}}else{alert(notice_message);}}}})(jQuery);

/*** Default Text ***********************/
;(function($){$.fn.real_val=$.fn.val;$.fn.val=function(v){var $this=$(this);if(typeof v=='undefined'){if($this.watch_state('changed')===false){r='';}else{r=$this.real_val(v);}}else{r=$this.real_val(v);$this.trigger('changed');}return r;};$.fn.default_text=function(default_text,options){var settings=$.extend({cssClass:'default-text',persistent:false},options);this.watch_state('focused','focus','blur',false).watch_state('changed','changed','defaulted',false).each(function(){var $this=$(this);$this.data('default_text',default_text);if($this.real_val()==''){$this.real_val($this.data('default_text'));}else{$this.trigger('changed');}$this.bind('defaulted changed',function(){$this.toggleClass(settings.cssClass,!$this.watch_state('changed'));}).bind('focus',function(){if(!$this.watch_state('changed')&&!settings.persistent){$this.val("");}else{$this.trigger('changed');}}).bind('blur',function(){if(settings.persistent&&$this.real_val()==$this.data('default_text')){$this.val("");}if($this.val()==''){$this.real_val($this.data('default_text'));$this.trigger('defaulted');}}).parents('form').bind('submit',function(){if($this.watch_state('focused')){$this.trigger('blur');}if(!$this.watch_state('changed')){$this.real_val('');}});}).trigger('blur');return this;}})(jQuery);

/*** Buttons ****************************/
;(function($){$(function(){$('button[disabled]').addClass('disabled');$('a.button').each(function(){var old_button=$(this);var location=old_button.attr("href");var button=$('<button type="button"></button>').text(old_button.text()).attr({'target':old_button.attr("target"),'rel':old_button.attr("rel"),'id':old_button.attr("id"),'class':old_button.attr("class")}).removeClass("button").bind('click',function(){if($(this).attr('disabled')!='disabled'){if($(this).attr('target')){window.open(location,$(this).attr('target'));}else{window.location=location;}}});if(button.hasClass('disabled')){button.attr('disabled','disabled');}old_button.after(button);old_button.remove();});});})(jQuery);

// Change all this stuff after we redo how things work


$(function(){
	$('.confirm_link').bind('click', function(){
		return confirm('Are you sure you want to ' + $(this).attr('title') + '?');
	});
});


/********************************
*  BROWSING                     *
*********************************/

// Submit a hidden form after asking question
function submit_form_request(form_id, question_id) {

	// Get the question from a hidden field in the form
	ask_question = $("#" + question_id).text();

	// Ask the question and force a YES response
	if (confirm(ask_question)) {
		$("#" + form_id).submit();
	}

}

// Submit a hidden form after asking question with checkbox selection
function submit_form_request_checkbox(form_id, source_form_id, question_id) {

	// Get the selected Checkboxes
	ids = get_selected_checkboxes(source_form_id);

	// If there were IDs selected
	if (ids != "") {

		// If no question was passed
		if (question_id == undefined) {

			// Submit the form
			$("#" + form_id + " [name='selected_ids']").val(ids);
			$("#" + form_id).submit();

		} else {

			// Get the question from a hidden field in the form
			ask_question = $("#" + question_id).text();

			// Ask the question and force a YES response
			if (confirm(ask_question)) {
				$("#" + form_id + " [name='selected_ids']").val(ids);
				$("#" + form_id).submit();
			}

		}

	} else {
		alert ("You did not select any checkboxes.");
	}

}

//Get selected check boxes of a form
function get_selected_checkboxes(container_id) {

	// Hold a comma seperated list of IDs
	ids = "";

	// Loop through each checkbox within our container
	$("#" + container_id + " :checked").not(".checkall").each( function () {
		ids += "," + $(this).val();
	});

	// Return list of IDs, remove beginning comma
	return ids.substr(1);

}

// Check or Uncheck checkboxes of a container
function check_uncheck_all(container_id, self_id) {
	$("#" + container_id + " input[type='checkbox']").not(':disabled').attr('checked', $("#" + self_id).is(':checked'));
}

