//MAIN JAVASCRIPT FUNCTIONS FILE//
//////////////////////////////////
function autotab(original,destination){
    if (original.getAttribute && original.value.length == original.getAttribute("maxlength"))
        destination.focus()
}

function MM_jumpMenu(targ,selObj,restore){
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function getformvalues(fobj){
        
    var str = "";
    proceed = true;
    var objID = document.getElementById(fobj);

    for(var i = 0; i < objID.elements.length; i++){
        
        //PRE-SUBMISSION VALIDATION CHECK - BASED ON RESULTS OF AJAX VALIDATION
        var chkid = objID.elements[i].id + "_check";
        //WEED OUT FORM FIELDS WITHOUT "id" VALUES
        if(chkid != "_check" && trim(chkid) != ""){
            var chkvar = document.getElementById(chkid);
            //WEED OUT FIELDS WITHOUT HIDDEN INPUTS "_check's"
            if(chkvar != null){
                var chkval = chkvar.value;
                if(proceed == true){
                    if(chkval == "false"){
                        proceed = false;        
                    }
                }

            }
             
        }

        if(objID.elements[i].type == "checkbox" && objID.elements[i].value == ""){
            str += objID.elements[i].name + "=" + objID.elements[i].checked + "&";
        }else if(objID.elements[i].type == "checkbox" && objID.elements[i].value != ""){
        	
        	if(objID.elements[i].checked == true){
        		str += objID.elements[i].name + "=" + escape(objID.elements[i].value) + "&";
        	}
        	
        }else if(objID.elements[i].type == "select-multiple" && objID.elements[i].id.substr(-9,9) == "_selected"){

            str += objID.elements[i].name + "=";
            var list = document.getElementById(objID.elements[i].id);
            
            for(var w = 0; w < list.length; w++){
                if(w > 0){
                    str += ",";
                }
                str += list.options[w].value;
            }
            str += "&";
        }else if(objID.elements[i].type == "radio"){
        	
        	if(objID.elements[i].checked){
        		 str += objID.elements[i].name + "=" + escape(objID.elements[i].value) + "&";
        	}
           
        }else{
            str += objID.elements[i].name + "=" + escape(objID.elements[i].value) + "&";
        }        
    }
    return str;

}
    
function error_modal(mtitle, mmsg, msg_class){

	if(!msg_class){
		msg_class = "text_red";
	}

	$("#modal_title").html(mtitle);
	var epage = root_path + "gen_tools/mod_ajax-error_modal.php";
	var estr = "error_msg=" + mmsg;
	
	$.ajax({	
    	type: "POST",
    	url: epage,
    	data: estr,
    	dataType: "html",
    	success: function(data){
			$("#modalbody").html(data);
			$("#close_butt").click(function(){
				close_modal();
			});
	    },
	    complete: function(data){
            //console.log(data);
			if(msg_class != "text_red"){
				$("#error_modal_msg").removeClass("text_red");
				$("#error_modal_msg").addClass(msg_class);
			}
            show_modal();
	    }
	});
}

// If user clicks confirm button, call function callback with input context.
function confirm_modal(callback_func, context, mmsg, mtitle, msg_class, options){

    if(!mtitle) {
        mtitle = "Confirmation";
    }
        
    if(!mmsg) {
        mmsg = "Are you sure?";
    }
    
    if(!options) {
        options = ["Yes", "No"];
    } else {
        if(!options[0]) {
            options[0] = "Yes";
        }
        
        if(!options[1]) {
            options[1] = "No";
        }
    
    }

	if(!msg_class){
		msg_class = "text_red";
	}

	$("#modal_title").html(mtitle);
	var epage = root_path + "gen_tools/mod_ajax-confirm_modal.php";
	var estr = "confirm_msg=" + mmsg + "&option1=" + options[0] + "&option2=" + options[1];
	
	$.ajax({	
    	type: "POST",
    	url: epage,
    	data: estr,
    	dataType: "html",
    	success: function(data){
				$("#modalbody").html(data);
	    },
	    complete: function(){
			
			$("#confirm_butt").click(function(){
                //close_modal();// This is weird. It should close the confirm modal but when it is used like this is is closing/preventing potential error modals from popping up. If I move the close_modal() call to the callback function (delete_user(userid) in this case) it works kinda wierd and doesn't make semantic sense (it shouldn't close the conf modal since it didn't call it, but was called by it).

                // Ok, this is working, but callback_func must not be async. Look into making this more general later. 
				if(callback_func(context) === false) { error_modal("ERROR", "There has been an error. Please contact EPG."); } else { close_modal(); }
			});			
			$("#cancel_butt").click(function(){
				close_modal();
			});
			if(msg_class != "text_red"){
				$("#confirm_modal_msg").removeClass("text_red");
				$("#confirm_modal_msg").addClass(msg_class);
			}
            show_modal();			
/*
			$('#modal').addClass('modal');
			$.blockUI({message: $("#modal")});
*/
	    }
	});
}

function checkEnter(e){ //e is event object passed from function invocation
	var charcode;
    if(e && e.which){
        charcode = e.which
    }else{
        charcode = event.keyCode
    }

    if(charcode == 13){
        return true;
    }else{
        return false;
    }
}

function disable_ff_enter(e){
	if(checkEnter(e)){
		return false;
	}
}

function ajax_field_pop(serverpage, divid){
	var pstr = serverpage.split("?");
    var dopage = root_path + pstr[0];
	var str = pstr[1];
	$.ajax({	
    	type: "POST",
    	url: dopage,
    	data: str,
    	dataType: "html",
    	success: function(data){
			$("#" + divid).html(data);
	    }
	});
}

function close_modal(){
    $("#modal").hide();
    $("#modal").removeClass("modal_wide"); 
    $('#modal').addClass('modal');
    $("body").removeClass("bodyminheight"); 
    $.unblockUI(); 
    $("#blockui").hide();
}

function show_modal() {
    if(!$("#modal").is(':visible')) {
        $('#modal').addClass('modal');
        $.blockUI({message: $("#modal")});
    }
}

function do_approval_form(objID, program, reg_id, mfr_prog, ctrl_domain, brreg_var, brand_reg){
	
	var pos = $("#" + objID).position();
	var width = $("#" + objID).width();

	var dopage = root_path + "user_mgmt/mod_approval-menu.php";
	var str = "program=" + program + "&reg_id=" + reg_id + "&mfr_prog=" + mfr_prog + "&brreg_var=" + brreg_var + "&brand_reg=" + brand_reg + "&ctrl_domain=" + ctrl_domain;

	$.ajax({	
    	type: "POST",
    	url: dopage,
    	data: str,
    	dataType: "html",
    	success: function(data){
			$("#approval_menu").html(data);
	    },
		complete: function(){
			$("#approval_menu").css({"position":"absolute", "left": (pos.left + width - 2) + "px", "top": pos.top + "px"});
			$("#approval_menu").show();    
			
			$(".close_this").click(function(){
				$("#approval_menu").hide();
			});
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("THERE HAS BEEN AN ERROR - do_approval_form: " + textStatus + " - " + errorThrown);
		}
	});

}

function submit_modal_form(formname, serverpage, errordiv, errorpage){
	
	//var str = $("form#" + formname).serialize();
	//alert(ser);
	
    var str = getformvalues(formname);
    if(proceed == true){
        var objID = "modalbody";
        var dopage = root_path + serverpage;
    }else{
        var objID = errordiv
        var dopage = root_path + errorpage;   
    }
    
    $.ajax({	
    	type: "POST",
    	url: dopage,
    	data: str,
    	dataType: "html",
    	success: function(data){
			$("#" + objID).html(data);
	    },
	    error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("THERE HAS BEEN AN ERROR - submit_modal_form: " + textStatus + " - " + errorThrown);
		}
	});
    
}

function check_email(purpose){

    var estr = getformvalues("form_email");
   
    if(proceed == true){
        
        var epage = root_path + "user_mgmt/form_ajax-registration.php";
        
        $.ajax({
        	type: "POST",
        	url: epage,
        	data: estr,
        	success: function(data){
        		$("#modalbody").html(data);
        		CountryType();       	
        	}
        });
               
    }else{
        var obj = "reg_msg";
        var dopage = root_path + "user_mgmt/mod_ajax-formerror.php";
        dotheajax(dopage, obj, "POST", estr, "innerHTML");
    }
    
}

function field_match(field1id, field2id, gid){
        
    var val1 = document.getElementById(field1id).value;
    var val2 = document.getElementById(field2id).value;

    if(val1 != "" && val2 != "" && val2 == val1){
        document.getElementById(gid).innerHTML="<img src='../images/forms/valid_plus.gif' /><input type='hidden' name='" + field2id + "_check' id='" + field2id + "_check' value='true'>";     
    }else{
        document.getElementById(gid).innerHTML="<img src='../images/forms/valid_minus.gif' /><input type='hidden' name='" + field2id + "_check' id='" + field2id + "_check' value='false'>";  
    }
}

function validate(fieldname, thevalue, gid){
	if (fieldname == "req_ew" || fieldname == "req_cl" || fieldname == "req_ag" || fieldname == "req_tr" ) {
		var f0 = document.getElementById("req_ew");
		var f1 = document.getElementById("req_cl");
		var f2 = document.getElementById("req_ag");
		var f3 = document.getElementById("req_tr");
		str = "fname0=" + f0.name + "&fvalue0=" + f0.checked + "&fname1=" + f1.name + "&fvalue1=" + f1.checked + "&fname2=" + f2.name + "&fvalue2=" + f2.checked + "&fname3=" + f3.name + "&fvalue3=" + f3.checked;	
	} else {
		str = "fname=" + fieldname + "&fvalue=" + thevalue;
	}
	
    var serverpage = root_path + "user_mgmt/errchk_registration.php";
    var obj = gid;

    dotheajax(serverpage, obj, "POST", str, "innerHTML");
}

function validate_field(fieldname, thevalue, gid, val_page){
    var serverpage = root_path + val_page;
    var str = "fname=" + fieldname + "&fvalue=" + thevalue;
    var obj = gid;
    dotheajax(serverpage, obj, "POST", str, "innerHTML");
}

function validate_add_remove(fieldname){
    var list = document.getElementById(fieldname);
    var valfield = document.getElementById(fieldname + "_check");
    if(list.length >= 1){
        valfield.value = "true";
    }else{
        valfield.value = "false";
    }
}

function validate_country(thevalue, gid){

    if(thevalue == "United States"){
        document.getElementById("province_valid").innerHTML = "<input type='hidden' name='province_check' id='province_check' value='true'>";
    }else if(thevalue == "Canada"){
        document.getElementById("state_valid").innerHTML = "<input type='hidden' name='state_check' id='state_check' value='true'>";
    }
    
    var serverpage = root_path + "user_mgmt/errchk_registration.php";
    var str = "fname=country&fvalue=" + thevalue;
    var obj = gid;
    dotheajax(serverpage, obj, "POST", str, "innerHTML");
}

function validate_sec_answer(answer, gid){
    var email = $("#my_email").val(); 
    var serverpage = root_path + "user_mgmt/errchk_sq.php";
    var str = "sa=" + answer + "&my_email=" + email;
    var obj = gid;
    dotheajax(serverpage, obj, "POST", str, "innerHTML");
}

function validate_email_exists(email, gid){
    var email = $("#email_address").val(); 
    var serverpage = root_path + "user_mgmt/errchk_email_exists.php";
    var str = "email_address=" + email;
    var obj = gid;
    dotheajax(serverpage, obj, "POST", str, "innerHTML");
}

function do_modal_form(title, serverpage, validate_form, not_closeable){
	
	var pstr = serverpage.split("?");
    var dopage = root_path + pstr[0];
	var str = pstr[1];
	$.ajax({	
    	type: "POST",
    	url: dopage,
    	data: str,
    	dataType: "html",
    	success: function(data){
			$("#modalbody").html(data);
	    },
		complete: function(){
    		$("#modal_title").html(title);
    		$.blockUI({message: $("#modal")});
    		
			if(not_closeable) { 
				$("#modal_close").html("<< Return Home");
				$("#modal_close").css("color", "Blue");				
				$("#modal_close").attr('href', root_path + 'ew/index.php?control=home&quotelist=quotes'); 
			}
			if(validate_form != "false"){
				
		    	var objID = document.getElementById(validate_form);
			    for(var i = 0; i < objID.elements.length; i++){
			        
			        var fieldname = objID.elements[i].id;
			        if(fieldname != '' && fieldname.substr(-6, 6) != "_check" && document.getElementById(fieldname + '_valid') != null && fieldname.substr(-9, 9) != "_selected"){
			            value = document.getElementById(fieldname).value;
			            validate(fieldname, value, fieldname + '_valid');
			        }
			        
			    }

		    }
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert("THERE HAS BEEN AN ERROR - do_modal_form: " + $(this).attr('id') + textStatus + " - " + errorThrown);
		}
	});
    
}

function add_program(){
    var email = $("#email_1").val();
    var ew_val = document.form_prog.add_ew.checked;
    var cl_val = document.form_prog.add_cl.checked;
    var tr_val = document.form_prog.add_tr.checked;
    
    if(ew_val == true || cl_val == true || tr_val == true){
        var progpage = root_path + "user_mgmt/bot_add-programs.php";
        var progstr = "email=" + email + "&ew_val=" + ew_val + "&cl_val=" + cl_val + "&tr_val=" + tr_val;
        var obj = "modalbody";
        dotheajax(progpage, obj, "POST", progstr, "innerHTML");
    }else{
        $("#reg_msg").html("<span class='text_red'><b>Please choose a program.</b></span>");
    }
}

function CountryType()
{

	if($("#my_country").val() == 'United States')
	{
	   $("#tr_no_country_id").hide();
	   $("#tr_canada_id").hide();
	   $("#tr_usa_id").show();
	}
	
	if($("#my_country").val() == 'Canada')
	{
	   $("#tr_no_country_id").hide();
	   $("#tr_canada_id").show();
	   $("#tr_usa_id").hide();
	}
	
	if($("#my_country").val() == '')
	{
	   $("#tr_no_country_id").show();
	   $("#tr_canada_id").hide();
	   $("#tr_usa_id").hide();
	}

}

function compare_select_text(a, b) {
    var textA = a.text.toLowerCase( );
    var textB = b.text.toLowerCase( );
    if (textA < textB) {return -1}
    if (textA > textB) {return 1}
    return 0;
}

function move_option(src_id, target_id, validate)
{
    var tmp_src_opts = new Array();
    var target_add = new Array();
    var target_orig = new Array();
    var x = 0;
    var q = 0;
    var j = 0;
    
    var optsrc = document.getElementById(src_id);
    var opttarg = document.getElementById(target_id);
    
    for (var i = 0; i < optsrc.length; i++) {
        if (optsrc.options[i].selected) {
            var tmp_a_values = new Object();
            tmp_a_values.text = optsrc.options[i].text;
            tmp_a_values.value = optsrc.options[i].value;
            target_add[q] = tmp_a_values;
            q++;
        } else {
            //storing options that stay to recreate select element
            var tmp_values = new Object();
            tmp_values.text = optsrc.options[i].text;
            tmp_values.value = optsrc.options[i].value;
            tmp_src_opts[x] = tmp_values;
            x++;
        }
        
    }
    
    tmp_src_opts.sort(compare_select_text);
    //resetting length of source
    optsrc.length = tmp_src_opts.length;
    //looping through temp array to recreate source select element
    for (var i = 0; i < tmp_src_opts.length; i++) {
        optsrc.options[i].text = tmp_src_opts[i].text;
        optsrc.options[i].value = tmp_src_opts[i].value;
        optsrc.options[i].selected = false;
    }
    
    for (var i = 0; i < opttarg.length; i++) {
        var tmp_o_values = new Object();
        tmp_o_values.text = opttarg.options[i].text;
        tmp_o_values.value = opttarg.options[i].value;
        target_orig[j] = tmp_o_values;
        j++;
    }  
    
    var target_values = target_orig.concat(target_add);
    target_values.sort(compare_select_text);
    opttarg.length = target_values.length;
    for (var k = 0; k < target_values.length; k++) {
        //alert(target_values[k].text + " " + target_values[k].value);
        opttarg.options[k].text = target_values[k].text;
        opttarg.options[k].value = target_values[k].value;
        opttarg.options[k].selected = false;
    }
    
    if(validate == "target"){
        validate_add_remove(target_id);  
    }else if(validate == "source"){
        validate_add_remove(src_id);
    }
}


function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

function noBack() {
	try {
		window.history.forward();
	} catch (e) {
		//Ignore
	}
}

function addLoadEvent(func) { 
	  var oldonload = window.onload; 
	  if (typeof window.onload != 'function') { 
	    window.onload = func; 
	  } else { 
	    window.onload = function() { 
	      if (oldonload) { 
	        oldonload(); 
	      } 
	      func(); 
	    } 
	  } 
}

function get_brand_phone(mfr_program, brand) {
    	if(mfr_program === "CNH") {
        	var hotline = {"Case" : "866.606.1517",
        				"Case IH" : "866.606.1802",
        			"New Holland" : "866.606.1807",
       "New Holland Construction" : "866.606.1798",
        				"Kobelco" : "866.606.1806",
        					"PPP" : "866.606.1806" };
        	if(hotline[brand] === undefined) {
        		brand = "PPP";
        	}									
    	} else if(mfr_program === "PPSP") {
    		var hotline = {"Protection Point" : "1-888-952-5511"}
        	if(hotline[brand] === undefined) {
        		brand = "Protection Point";
        	}										
    	} else if(mfr_program === "BOBCAT") {
    		var hotline = {"Bobcat Dealer Toll Free Help Desk" : "(855) 663-4127"}    		
        	if(hotline[brand] === undefined) {
        		brand = "Bobcat Dealer Toll Free Help Desk";
        	}
    	} else { 
    		var hotline = {"Extended Services" : "(901) 251-1718"}
        	if(hotline[brand] === undefined) {
        		brand = "Extended Services";
        	}					
    	}
    return {"hotline" : hotline, "brand" : brand};		
}

function build_select(val_array, name_id, leader, default_opt, cl_string){
	//alert(name_id + " ---> " + cl_string);

	var select_html = "";
	var classes = "inputbox";
	if(cl_string != null && cl_string != ""){
		classes += " " + cl_string;
	}
	
	select_html += "<select class=\"" + classes + "\" name=\"" + name_id + "\" id=\"" + name_id + "\">";
	
	if(leader != "" && leader != null && leader != undefined){
		select_html += "<option value=\"\">" + leader + "</option>";
	}
	
	for(key in val_array) {
		var select_val = "";
		//alert(val_array[key] + " - " + default_opt)
		if(key == default_opt) { 
			select_val = "selected";
		}
		select_html += "<option value='" + key + "' " + select_val + " >" + val_array[key] + "</option>";
	}
	
	select_html +="</select>";
	return select_html;
}

function build_locked(name_id, value){
	var locked_html = "<input type=\"hidden\" name=\"" + name_id + "\" id=\"" + name_id + "\" value=\"" + value + "\">";
	locked_html += "<b/>" + value + "</b>";
} 

function dotheajax(phpfile, obj, getpost, str, response){

	$.ajax({	
    	type: getpost,
    	url: phpfile,
    	data: str,
    	dataType: "html",
    	success: function(data){
			 if(response == "value"){
			 	$("#" + obj).val(data);
			 } else if(response != "none"){
			 	$("#" + obj).html(data);
			 }
	    }
	});
	
}

function close_object(object_id){
	$("#" + object_id).hide();
}

function ew_coverage_select(form, menu, rate_db, equip_db, quote_type, equip_usage,  mfr_program, special_program, language, dependent, lookup, leader, default_val, next_opts){
		
	var these_opts = next_opts[menu];

	var next_menu = these_opts.next_menu;
	var next_dependent = these_opts.next_dependent;
	var next_default = these_opts.next_default;
	var next_leader = these_opts.next_leader;
	var classes = these_opts.classes;
	
	var the_mfr_program = mfr_program;
	var the_special_program = special_program;
	var the_quote_type = quote_type;
	var the_equip_usage = equip_usage;
	
	var dopage = root_path + "ew/bot_ajax_build-coverage-selects.php";

	var str = "form=" + form + "&menu=" + menu + "&rate_db=" + rate_db + "&equip_db=" + equip_db;
	str += "&language=" + language + "&lookup=" + lookup + "&mfr_program=" + the_mfr_program;
	str += "&quote_type=" + quote_type + "&equip_usage=" + equip_usage + "&special_program=" + special_program;
	
	if($.isArray(dependent)){
		
		for(var i = 0; i < dependent.length; i++){
			str += "&dependent"
			if(i > 0){
				str += i;
			}
			str += "=" + dependent[i];
		}
		
	}else{
		str += "&dependent=" + dependent;	
	}
	
	//alert(dopage + "?" + str);
	
	$.ajax({
    	type: "POST",
    	url: dopage,
    	data: str,
    	dataType: "json",
    	success: function(data){
    	
    		if(data['locked'] === "true"){
    			var output_menu = build_locked(menu, data['value']);
    		}else{
    			var output_menu = build_select(data, menu, leader, default_val, classes);	
    		}
    	
    		 
    		$("#" + menu + "_area").html(output_menu);	
    		
    		if($("#" + menu).val() === ""){
    			$("." + menu + "_empty").hide();
    		}
    	},
    	complete: function(){
    		
    		if(next_default != "" && next_default != null || next_menu != "none" && default_val != "" && default_val != null){
    			ew_coverage_select(form, next_menu, rate_db, equip_db, quote_type, the_equip_usage, the_mfr_program, the_special_program, language, $("#" + next_dependent).val(), "1", next_leader, next_default, next_opts);
    			$("." + menu + "_select").show();
    		}
    		
    		$("#" + menu).change(function(){
				if($("#" + menu).val() != ""){
					if(next_menu != "none"){
						
						if($.isArray(next_dependent)){
							
							var this_next_dep = {};
							for(var i = 0; i < next_dependent.length; i++){
								$.extend(this_next_dep, $("#" + next_dependent[i]).val());
							}
							
						}else{
							var this_next_dep = $("#" + next_dependent).val();	
						}
					
						ew_coverage_select(form, next_menu, rate_db, equip_db, quote_type, the_equip_usage, the_mfr_program, the_special_program, language, this_next_dep, "1", next_leader, next_default, next_opts);
					}
					$("." + menu + "_select").show();	
				}else{
					$("." + menu + "_empty").hide();
				}
			});
    	},
    	error: function(XMLHttpRequest, textStatus, errorThrown){
    		alert("THERE HAS BEEN AN ERROR - ew_coverage_select: " + textStatus + " - " + errorThrown);
    	}
    });
}
