// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
// public/javascripts/application.js

var graph_year_data = []

//Fix IE not implementing array.indexOf
if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}

jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

/* Document preparation */
$(document).ready(function() {	

  $('#error-display').hide();
  $('select').addClass('general_input');
  $('input:text').addClass('general_input');
  
  /* Printing handler */
  $("#print-button").onclickPrintButton();
  
  /* Table/Graph tab control */
  $('#tab-menu div a').click(function(){ //When any link is clicked
      toggleTab(this);
      return false;
  });
  
  $('#tab-menu div a').mousedown(function(){ //When any link is clicked
      this.blur();
      return false;
  });
  
  // update first tab
  toggleTab($(".tab-menu-active"));
  
  /* Selection Box changes */
  $("#state_code").onchangeStateCode();  
  $("#county_code").onchangeCountyCode();
  $("#grid_ids").onchangeGridID();
  //$("#configuration-panel").onchangeConfigurationForm();
  $("#graph-info input:radio,input:checkbox").onclickConfigurationFormOption();
  $("#graph-info select").onchangeConfigurationForm();
  $("#graph-options input:radio").onclickConfigurationFormOption();
  $("#graph_options input:checkbox").onclickConfigurationFormOption();
  $("#calculate").onCalculateTableData();
  
  if ($("#grid_ids").val() == 'Please Select') {
		// disable controls
		$("#protection-info input").disableInput();
		$("#protection-info select").disableInput();  
		$("#graph-info input").disableInput();
		$("#graph-info select").disableInput();  
		$("#results-panel input").disableInput();
  } else {
  	updateGraph();
  }
  
  $('#error-display').hide();
  
  /* Validation of Integer inputs */
  $("input:text").keyup( function(event){
  	validateIntegerText(this, true);
  });
  
  $(".table_input:text").focus( function () {
  	updateOverlappingIntervals();
  });
  $(".table_input:text").keyup( function() {
  	updateOverlappingIntervals();
  });
  updateOverlappingIntervals();
  
  //save graphs years for manipulation later
  $.each($("#begin_year option"), function(index, opt) {
  	graph_year_data.push($(opt).val());
  });
  
  updateMinMaxYearSelectBoxes();
  
  /* IE select box disabled fix */
  if (jQuery.browser.msie) {
  	$("select").each(function() {
		$(this).onchangeSelectBox();
	});
  }
  
  setupIntervalPopup();
})

function setupIntervalPopup()
{
	$(".simple_popup_info").each(function(){
        $(this).css("display","none").siblings(".simple_popup").click(function(){
            $(".simple_popup_div").remove();
            var strSimple = "<div class='simple_popup_div'><div class='simple_popup_inner'>";
            strSimple += "<p class='simple_close'><a href='#'>Close[ x ]</a></p>";
            strSimple += $(this).siblings(".simple_popup_info").html();
            strSimple += "</div></div>";
            $("body").append(strSimple);
            
			var offset = $(this).offset();
			$(".simple_popup_div").css("left", offset.left);
			$(".simple_popup_div").css("top", offset.top + $(this).height());

            $(".simple_close").click(function(){
                $(".simple_popup_div").remove();
                return false;
            });
            return false;
        });
    });
}

function clearGrid(disable_inputs)
{
	jQuery.ajax({type: "GET", url: "/prf/load_data_table", datatype: "script", success: function(ob){
			
			$("#table-view").html(ob);
			
			//reattach event handler and styles
			$("#calculate").onCalculateTableData();
			$('select').addClass('general_input');
  			$('input:text').addClass('general_input');
			
			$("#results-panel input").keyup( function(event){
				validateIntegerText(this, true);
			});
			$(".table_input:text").focus( function () {
  				updateOverlappingIntervals();
  			});
			$(".table_input:text").keyup( function() {
  				updateOverlappingIntervals();
  			});
			updateOverlappingIntervals();
			setupIntervalPopup();
			
			if( disable_inputs == true)
			{
				$("#configuration-panel input").disableInput();
				$("#configuration-panel select").disableInput();
				$("#results-panel input").disableInput();
			}
		}
	});
}

/* Handle updating of Table and Graph based on configuration form input */
function getConfigPanelParams(params) {
	$(".config_panel_input[type!=checkbox][type!=radio][type!=text]").each(function() {
		params[$(this).attr('id')] = $(this).val();
	});
	$(".config_panel_input[type=checkbox]").each(function() {
		params[$(this).attr('id')] = $(this).attr('checked');
	});
	$(".config_panel_input:radio:checked").each(function() {
		params[$(this).attr('name')] = $(this).attr('value');
	});
	$(".config_panel_input:text").each(function(){
		params[$(this).attr('name')] = $(this).attr('value');
	});
	return params;
};

/*Gets parameters from the Table div (interval values)*/
function getTableParams(params) {
	$(".table_input").each(function() {
		params[$(this).attr('name')] = $(this).val();
	});
	return params;
};

/*Gets parameters from the Graph div  (chart/graph type, animation)*/
function getGraphParams(params){
	$(".graph_options:input:radio:checked").each(function() {
		params[$(this).attr('name')] = $(this).attr('value');
	});

	$(".graph_options:input:checkbox").each(function() {
		params[$(this).attr('id')] = $(this).attr('checked');
	});
	return params;
}

/*Gets parameter associated with what tab is visible */
function getActiveTabParam(params) {
	if ($("#tab-sel-1").hasClass("tab-menu-active")) {
		params["active_tab"] = 'table';
	} else {
		params["active_tab"] = 'graph';
	}
}

function updateMinMaxYearSelectBoxes() {
	//Get selected begin_year and end_year
	var selected_begin_year = $("#begin_year").val();
	var selected_end_year = $("#end_year").val();
	
	if (selected_begin_year != null && selected_end_year != null && selected_begin_year != "Select" && selected_end_year != "Select") {
		//Check if the end year is earlier than the begin year, update it if so
		var begin_year_index = graph_year_data.indexOf(selected_begin_year);
		var end_year_index = graph_year_data.indexOf(selected_end_year);
		if (end_year_index > begin_year_index) {
			selected_end_year = graph_year_data[begin_year_index];
		}
		
		if (begin_year_index != -1 && end_year_index != -1) {
			//clear out end select box of years to keep order, then add years to end_year select box
			$("#end_year").removeOption(/^\d+/);
			$.each(graph_year_data, function(index, year){
				if (index != 0 && index <= begin_year_index) {
					var year_option = {}
					year_option["" + year] = year.toString()
					$("#end_year").addOption(year_option, year == selected_end_year);
				}
			});
		}
	}
}

function updateGraph()
{
	var url = "/prf/load_fusion_graph";
	var params = {};
	getConfigPanelParams(params);
	getTableParams(params);
	getGraphParams(params);
		
	jQuery.ajax({type: "GET", url: url, data: params, datatype: "script", 
	beforeSend: function(){
				//Add overlay and loading gif
				$("#results-content").show();
				$("#results-overlay").fadeIn("fast");
				
			},
	success: function(ob){
			$("#graph-view").html(ob);
			//reattach options change handler
			$("#graph-options input:radio").onclickConfigurationFormOption();
			$("#graph_options input:checkbox").onclickConfigurationFormOption();
		},
	complete: function() {
				//Remove Overlay
				$("#results-content").hide();
				$("#results-overlay").fadeOut("fast");
			}
	});
}

/* called when user toggles between table/graph */
function toggleTab ( el )
{
    $('#tab-menu div a').removeClass('tab-menu-active'); // Remove active class from all links
    $('#tab-menu div a').addClass('tab-menu-inactive');
    $(el).addClass('tab-menu-active'); //Set clicked link class to active  
    $(el).removeClass('tab-menu-inactive');
	$(el).blur();
	
	var curID = $(el).attr("id");
	if( curID == 'tab-sel-1')
	{
		$('#table-view').show();
		$('#graph-view').hide();
		updateOverlappingIntervals();
		
		$("#graph-info input").disableInput();
		$("#graph-info select").disableInput();
	}
	else
	{
		$('#table-view').hide();
		$('#graph-view').show();
		
		if ($("#grid_ids").val() != 'Please Select') 
		{
			$("#graph-info input").enableInput();
			$("#graph-info select").enableInput();
		}
	}
}

/* Loads counties on new State selection */
jQuery.fn.onchangeStateCode = function() {	
  this.change(function() {
	var selected = $("#state_code option:selected");  
	jQuery.ajax({type: "GET", url: "/prf/load_counties?state_code="+selected.val(),  datatype: "html", success: function(html){
		
		$("#county_code").replaceWith(html);
		
		// re-attach event
		$("#county_code").onchangeCountyCode();
		$("#county_code").addClass('general_input');
		
		// update grid_id selection by triggering change event of county_code
		var event = jQuery.Event("change");
		$("#county_code").triggerHandler(event);
		clearGrid(true);
	}
	});
    return false;
  })
  return this;
};

/* Loads grids on new County selection */
jQuery.fn.onchangeCountyCode = function() {
  this.change(function() {

	var selected = $("#county_code option:selected");  
	jQuery.ajax({type: "GET", url: "/prf/load_grids?county_code="+selected.val(),  datatype: "html", success: function(html){
		
		$("#grid_ids").replaceWith(html);
		$("#grid_ids").onchangeGridID();
		$("#grid_ids").addClass('general_input');
		
		// update controls
		if ($("#grid_ids").val() == 'Please Select') 
		{
			$("#protection-info input").disableInput();
			$("#protection-info select").disableInput();  
			$("#graph-info input").disableInput();
			$("#graph-info select").disableInput();  
			$("#results-panel input").disableInput();
		}
		clearGrid(true);
	}	
	})
	return false;
  })
  return this;
};

/* Handle setting of selected grid_id in controller */
jQuery.fn.onchangeGridID = function() {
  this.change(function() {
	var selected = $("#grid_ids option:selected");  
	jQuery.ajax({type: "GET", url: "/prf/set_grid_id?grid_id="+selected.val(),  datatype: "script", success: function(){
		//Update Config Panel
		var config_url = '/prf/load_config_panel';
		var config_params = {};
		getConfigPanelParams(config_params);
		jQuery.ajax({type: "GET", url: config_url, data: config_params, datatype: "html",
			success: function(html) {
				$('#configuration-panel').html(html);
				$("#graph-info input:radio,input:checkbox").onclickConfigurationFormOption();
  				$("#graph-info select").onchangeConfigurationForm();
				if (jQuery.browser.msie) {
					$("select").each(function(){
						$(this).onchangeSelectBox();
					});
				}
				// enable controls
				$("#protection-info input").enableInput();
				$("#protection-info select").enableInput();  
				if ($(".tab-menu-active").attr('id') == 'tab-sel-1') {
					$("#graph-info input").disableInput();
					$("#graph-info select").disableInput();
				} else {
					$("#graph-info input").enableInput();
					$("#graph-info select").enableInput();
				}
				$("#results-panel input").enableInput();
				clearGrid(false);
				//save graphs years for manipulation later
				$.each($("#begin_year option"), function(index, opt) {
					graph_year_data.push($(opt).val());
				});
				updateMinMaxYearSelectBoxes();
				updateGraph();	
			}
		});
	}	
	});
    return false;
  })
  return this;
};

jQuery.fn.onclickConfigurationFormOption = function() {
	this.click(function() {
		updateMinMaxYearSelectBoxes();
		updateGraph();
		return true; //Returning true changes the value of the checkbox / radio button
	});
	return this;
};

jQuery.fn.onchangeConfigurationForm = function(){
	this.change(function() {
		updateMinMaxYearSelectBoxes();
		updateGraph();
		return false;
	});
	
	return this;
};

jQuery.fn.onCalculateTableData = function(){
	$(this).click(function(){
		
		//Wrap up parameters
		var params = {};
		getConfigPanelParams(params);
		getTableParams(params);
		//call AJAX
		jQuery.ajax({type: "GET", url: "/prf/load_data_table", data: params, datatype: "html",
			beforeSend: function(){
				//Add overlay and loading gif
				$("#results-content").show();
				$("#results-overlay").fadeIn("fast");				
			},
			success: function(html) {
				$("#table-view").html(html);
				//reattach event handler and styles
				$("#calculate").onCalculateTableData();
				$('select').addClass('general_input');
	  			$('input:text').addClass('general_input');
				
				$("#results-panel input").keyup( function(event){
				  	validateIntegerText(this, true);
				});
				$(".table_input:text").focus( function () {
			  		updateOverlappingIntervals();
  				});
				$(".table_input:text").keyup( function() {
  					updateOverlappingIntervals();
  				});
				updateOverlappingIntervals();
				
				setupIntervalPopup();
				// error checking?  
				checkErrors();	
			},
			complete: function() {
				//Remove Overlay
				$("#results-content").hide();
				$("#results-overlay").fadeOut("fast");
			} 
		});
		return false;
	});
	return this;
};

function checkErrors()
{
	jQuery.ajax({type: "GET", url: "/prf/load_error", datatype: "script", success: function(ob){
				
			$('#error-display').html(ob);
			$('#error-display').show();
		}
	});
}

/* disables input control */
jQuery.fn.disableInput = function() {
	$(this).attr("disabled","disabled");
};

/* enables input control */
jQuery.fn.enableInput = function() {
	$(this).removeAttr("disabled");
};

// Validates a single Numeric text field to see if value is a integer
function validateIntegerText(textbox, required)
{
    var valid = true;  
	var value = $(textbox).val();      
    //Check if it is required or not
    if(value == "" && required==false){
        $(textbox).css('backgroundColor', '');
        return true;
    }
	if (value != '-') {
		var intVal = parseInt(value);
		if (isNaN(intVal)) {
			valid = false;
		}
		
		if (valid) {
			if (intVal < 0) {
				valid = false;
			}
		}
	}
    
    if (!valid){
        $(textbox).css('backgroundColor','#F69484');
    } else {
        $(textbox).css('backgroundColor','');
    }
    return valid;
};

function updateOverlappingIntervals() {
	//go through all text boxes and find which ones have values and are shown
	if ($(".nav-menu-active").attr('id') == 'nav-sel-2') { //rainfall
		var valid_intervals = [false, false, false, false, false, false, false, false, false, false, false];
	} else { //vegetation
		var valid_intervals = [false, false, false, false, false, false, false, false, false, false];
	}
	valid_intervals = $.map(valid_intervals, function(valid, index) {
		var text_box = $("#table_input_" + (index + 1));
		if (text_box.length > 0) {
			text_box = text_box[0];
			var value = $(text_box).val();
			var hidden = $(text_box).css('display');
			return (value != '-' && (!(isNaN(parseInt(value)))) && parseInt(value) > 0 && hidden != 'none');
		}
		return false;
	});
	var displayed_intervals = $.map(valid_intervals, function(valid, index) {
		if ($(".nav-menu-active").attr('id') == 'nav-sel-2') { //rainfall
			var left = (index > 0) && valid_intervals[index - 1];
			var right = (index < 10) && valid_intervals[index + 1];
			return (!(left || right));
		} else {
			var left2 = (index > 1) && valid_intervals[index - 2];
			var left1 = (index > 0) && valid_intervals[index - 1];
			var right2 = (index < 8) && valid_intervals[index + 2];
			var right1 = (index < 9) && valid_intervals[index + 1];
			return (!(left2 || left1 || right1 || right2));
		}
		return false;
		
	});
	//go through text boxes setting hidden / show boxes
	$.each (displayed_intervals, function(index, displayed) {
		var visible = $("#table_input_" + (index + 1))
		if (visible.length > 0) {
			visible = $(visible[0]).css('display') != 'none';
			if (visible != displayed) {
				$(".table_input_" + (index + 1)).toggle();
			}
		}
	});
};

//Returns base url from the window
function getBaseURL() {
	var results = /\/rma\/(vi|ri)\/(api|prf)\/dst/.exec(window.location.href);
	if (results != null) {
		results = results [0];
	}
	return results;
}

//Converts a key value map into a string of url parameters
function convertToUrlParams(params) {
	var url_params = "?";
	$.each(params, function(key, value) {
		url_params += key + "=" + value + "&";
	});	
	//remove last '&'
	url_params = url_params.substring(0, url_params.length - 1);
	return url_params
}

//Printing Function
jQuery.fn.onclickPrintButton = function(){
	$(this).click(function() {
		var baseURL = getBaseURL();
		if (baseURL != null) {
			var params = {};
			getConfigPanelParams(params);
			getTableParams(params);
			getGraphParams(params);
			getActiveTabParam(params);
			window.open(baseURL + '/print' + convertToUrlParams(params), 'print_window', 'width=800,height=600,scrollbars=1,resizeable=1');
		}
		return false;
	});
	return this;
};

jQuery.fn.onchangeSelectBox = function() {
	var select_box = this;
	$(this).change(function() {
		$("#" + $(select_box).attr('id') + " option:selected").each(function() {
			if ($(this).attr('disabled') == true) {
				$("#" + $(select_box).attr('id') + " option:eq(1)").attr('selected', 'selected');
				var event = jQuery.Event("change");
				$("#" + $(select_box).attr('id')).triggerHandler(event);
			}
		});
	});
};

function showTableHelpDialog() {
	if ($(".nav-menu-active").attr('id') == 'nav-sel-2') { //rainfall
		showDialog('Help',
			"Acres cannot be insured in overlapping intervals. (rainfall intervals span two months)<br /><br />" +
	      	"For example, if acres are insured in interval IV, then intervals III and V are not available.<br /><br />" +
      		"For more information please <a href='http://agforceusa.com/api-decision-tool-info.pdf' target='_blank' class='table-more-info'>click here.</a>",
      		'success');
	} else {
		showDialog('Help',
			"Acres cannot be insured in overlapping intervals. (vegetation intervals span three months)<br /><br />" +
	      	"For example, if acres are insured in interval IV, then intervals II, III, V, and VI are not available.<br /><br />" +
      		"For more information please <a href='http://agforceusa.com/api-decision-tool-info.pdf' target='_blank' class='table-more-info'>click here.</a>",
      		'success');
	}
}

// global variables //
var TIMER = 50;
var SPEED = 100;
var WRAPPER = 'container';

// calculate the current window width //
function pageWidth() {
  return window.innerWidth != null ? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;
}

// calculate the current window height //
function pageHeight() {
  return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;
}

// calculate the current window vertical offset //
function topPosition() {
  return typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;
}

// calculate the position starting at the left of the window //
function leftPosition() {
  return typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;
}

// build/show the dialog box, populate the data and call the fadeDialog function //
function showDialog(title,message,type,autohide) {
  if(!type) {
    type = 'error';
  }
  var dialog;
  var dialogheader;
  var dialogclose;
  var dialogtitle;
  var dialogcontent;
  var dialogmask;
  if(!document.getElementById('dialog')) {
    dialog = document.createElement('div');
    dialog.id = 'dialog';
    dialogheader = document.createElement('div');
    dialogheader.id = 'dialog-header';
    dialogtitle = document.createElement('div');
    dialogtitle.id = 'dialog-title';
    dialogclose = document.createElement('div');
    dialogclose.id = 'dialog-close'
    dialogcontent = document.createElement('div');
    dialogcontent.id = 'dialog-content';
    dialogmask = document.createElement('div');
    dialogmask.id = 'dialog-mask';
    document.body.appendChild(dialogmask);
    document.body.appendChild(dialog);
    dialog.appendChild(dialogheader);
    dialogheader.appendChild(dialogtitle);
    dialogheader.appendChild(dialogclose);
    dialog.appendChild(dialogcontent);;
    dialogclose.setAttribute('onclick','hideDialog()');
    dialogclose.onclick = hideDialog;
  } else {
    dialog = document.getElementById('dialog');
    dialogheader = document.getElementById('dialog-header');
    dialogtitle = document.getElementById('dialog-title');
    dialogclose = document.getElementById('dialog-close');
    dialogcontent = document.getElementById('dialog-content');
    dialogmask = document.getElementById('dialog-mask');
    dialogmask.style.visibility = "visible";
    dialog.style.visibility = "visible";
  }
  dialog.style.opacity = .00;
  dialog.style.filter = 'alpha(opacity=0)';
  dialog.alpha = 0;
  var width = pageWidth();
  var height = pageHeight();
  var left = leftPosition();
  var top = topPosition();
  var dialogwidth = dialog.offsetWidth;
  var dialogheight = dialog.offsetHeight;
  var topposition = top + (height / 3) - (dialogheight / 2);
  var leftposition = left + (width / 2) - (dialogwidth / 2);
  dialog.style.top = topposition + "px";
  dialog.style.left = leftposition + "px";
  dialogheader.className = type + "header";
  dialogtitle.innerHTML = title;
  dialogcontent.className = type;
  dialogcontent.innerHTML = message;
  var content = document.getElementById(WRAPPER);
  dialogmask.style.height = content.offsetHeight + 'px';
  dialog.timer = setInterval("fadeDialog(1)", TIMER);
  if(autohide) {
    dialogclose.style.visibility = "hidden";
    window.setTimeout("hideDialog()", (autohide * 1000));
  } else {
    dialogclose.style.visibility = "visible";
  }
}

// hide the dialog box //
function hideDialog() {
  var dialog = document.getElementById('dialog');
  clearInterval(dialog.timer);
  dialog.timer = setInterval("fadeDialog(0)", TIMER);
}

// fade-in the dialog box //
function fadeDialog(flag) {
  if(flag == null) {
    flag = 1;
  }
  var dialog = document.getElementById('dialog');
  var value;
  if(flag == 1) {
    value = dialog.alpha + SPEED;
  } else {
    value = dialog.alpha - SPEED;
  }
  dialog.alpha = value;
  dialog.style.opacity = (value / 100);
  dialog.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(dialog.timer);
    dialog.timer = null;
  } else if(value <= 1) {
    dialog.style.visibility = "hidden";
    document.getElementById('dialog-mask').style.visibility = "hidden";
    clearInterval(dialog.timer);
  }
}

/*
 *
 * Copyright (c) 2006-2008 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.2.4
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 * $LastChangedDate: 2008-06-17 17:27:25 +0100 (Tue, 17 Jun 2008) $
 * $Rev: 5727 $
 *
 */
;(function(h){h.fn.addOption=function(){var j=function(a,f,c,g){var d=document.createElement("option");d.value=f,d.text=c;var b=a.options;var e=b.length;if(!a.cache){a.cache={};for(var i=0;i<e;i++){a.cache[b[i].value]=i}}if(typeof a.cache[f]=="undefined")a.cache[f]=e;a.options[a.cache[f]]=d;if(g){d.selected=true}};var k=arguments;if(k.length==0)return this;var l=true;var m=false;var n,o,p;if(typeof(k[0])=="object"){m=true;n=k[0]}if(k.length>=2){if(typeof(k[1])=="boolean")l=k[1];else if(typeof(k[2])=="boolean")l=k[2];if(!m){o=k[0];p=k[1]}}this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(m){for(var a in n){j(this,a,n[a],l)}}else{j(this,o,p,l)}});return this};h.fn.ajaxAddOption=function(c,g,d,b,e){if(typeof(c)!="string")return this;if(typeof(g)!="object")g={};if(typeof(d)!="boolean")d=true;this.each(function(){var f=this;h.getJSON(c,g,function(a){h(f).addOption(a,d);if(typeof b=="function"){if(typeof e=="object"){b.apply(f,e)}else{b.call(f)}}})});return this};h.fn.removeOption=function(){var d=arguments;if(d.length==0)return this;var b=typeof(d[0]);var e,i;if(b=="string"||b=="object"||b=="function"){e=d[0];if(e.constructor==Array){var j=e.length;for(var k=0;k<j;k++){this.removeOption(e[k],d[1])}return this}}else if(b=="number")i=d[0];else return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;if(this.cache)this.cache=null;var a=false;var f=this.options;if(!!e){var c=f.length;for(var g=c-1;g>=0;g--){if(e.constructor==RegExp){if(f[g].value.match(e)){a=true}}else if(f[g].value==e){a=true}if(a&&d[1]===true)a=f[g].selected;if(a){f[g]=null}a=false}}else{if(d[1]===true){a=f[i].selected}else{a=true}if(a){this.remove(i)}}});return this};h.fn.sortOptions=function(e){var i=h(this).selectedValues();var j=typeof(e)=="undefined"?true:!!e;this.each(function(){if(this.nodeName.toLowerCase()!="select")return;var c=this.options;var g=c.length;var d=[];for(var b=0;b<g;b++){d[b]={v:c[b].value,t:c[b].text}}d.sort(function(a,f){o1t=a.t.toLowerCase(),o2t=f.t.toLowerCase();if(o1t==o2t)return 0;if(j){return o1t<o2t?-1:1}else{return o1t>o2t?-1:1}});for(var b=0;b<g;b++){c[b].text=d[b].t;c[b].value=d[b].v}}).selectOptions(i,true);return this};h.fn.selectOptions=function(g,d){var b=g;var e=typeof(g);if(e=="object"&&b.constructor==Array){var i=this;h.each(b,function(){i.selectOptions(this,d)})};var j=d||false;if(e!="string"&&e!="function"&&e!="object")return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b.constructor==RegExp){if(a[c].value.match(b)){a[c].selected=true}else if(j){a[c].selected=false}}else{if(a[c].value==b){a[c].selected=true}else if(j){a[c].selected=false}}}});return this};h.fn.copyOptions=function(g,d){var b=d||"selected";if(h(g).size()==0)return this;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(b=="all"||(b=="selected"&&a[c].selected)){h(g).addOption(a[c].value,a[c].text)}}});return this};h.fn.containsOption=function(g,d){var b=false;var e=g;var i=typeof(e);var j=typeof(d);if(i!="string"&&i!="function"&&i!="object")return j=="function"?this:b;this.each(function(){if(this.nodeName.toLowerCase()!="select")return this;if(b&&j!="function")return false;var a=this.options;var f=a.length;for(var c=0;c<f;c++){if(e.constructor==RegExp){if(a[c].value.match(e)){b=true;if(j=="function")d.call(a[c],c)}}else{if(a[c].value==e){b=true;if(j=="function")d.call(a[c],c)}}}});return j=="function"?this:b};h.fn.selectedValues=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.value});return a};h.fn.selectedTexts=function(){var a=[];this.selectedOptions().each(function(){a[a.length]=this.text});return a};h.fn.selectedOptions=function(){return this.find("option:selected")}})(jQuery);
