/**
 * CHANGELOG:
 * KAB 20091207 - add change event to product search type, to switch between
 *			CONTAINS and EXACT depending on value
 * JRD 20100714 - add multi-CAS search to adv search page
 * JRD 20100728 - per JBS 7/28/2010 also check for CRLF to determine what to drop
 * DK  20110708 - removed invisible captcha from MSDS search and added comments
 * DK  20110712 - additional functionality for MSDS captcha
 */            


jQuery(document).ready(function () {

	var singleinputcas = $('[name=PSvalue]');
	var multipleinputcas = $('[name=PSvalue_mlt]'); 

	jQuery('.valignb').css('vertical-align', 'bottom');
	jQuery('.valignb').css('margin-left','5px');
	jQuery('#PSvalue_mlt').css('font-family','Arial,Helvetica,sans-serif');
	jQuery('#PSvalue_mlt').css('font-size','105%');

    jQuery('#srchtyp').change(function () {
    	type = jQuery(this).val();

        /*if (type == "PROD") {
        	jQuery('.filterrow').show();
        }
	else {
        	jQuery('.filterrow').hide();
	}*/

        if (type == "CAS") 
	    {
			jQuery('#srchHow').val('EXACT');
			jQuery('#PSvalue_mlt').show();
			jQuery('#PSvalue').hide();
			jQuery('#chineseText').hide();
			jQuery(".limitcas30").show();
	    }
	    else if (type == "PROD")
	    {
			jQuery('#srchHow').val('CONTAINS');
			jQuery(".limitcas30").hide();
			if (curLang.toUpperCase() == "ZH") {
				jQuery('#chineseText').show();
			}
			else {
				jQuery('#chineseText').hide();
			
			}
			jQuery('#PSvalue').show();
			jQuery('#PSvalue_mlt').hide();
			document.getElementById("productSearchButton").disabled=false;

        }
	    else
	    {
			jQuery('#srchHow').val('CONTAINS');
			jQuery('#chineseText').hide();
			jQuery('#PSvalue').show();
			jQuery('#PSvalue_mlt').hide();
			document.getElementById("productSearchButton").disabled=false;
			jQuery(".limitcas30").hide();
        }
        
        retainTerm();
    });

	function retainTerm() {
		// per JBS 2010.07/30 move value between PSvalue/PSvalue_mlt depending on type
		if(type == "CAS" && jQuery("#PSvalue_mlt").val() == "") {
			//var CAS = jQuery("#PSvalue").val();
			jQuery("#PSvalue_mlt").val(jQuery("#PSvalue").val());
			jQuery("#PSvalue").val('');
		}
		else if(type != "CAS" & jQuery("#PSvalue").val() == "")
		{
			var CAS = jQuery("#PSvalue_mlt").val();
			var CASL1 = CAS.indexOf(" ");
			var CASL2 = CAS.indexOf("\n");
			if(CASL1>=0 && (CASL1<=CASL2 || CASL2 == -1)) 
			{
				jQuery("#PSvalue").val(CAS.substring(0,CASL1)); 
			}
			else if(CASL2>=0 && (CASL2<=CASL1 || CASL1 == -1)) 
			{
				jQuery("#PSvalue").val(CAS.substring(0,CASL2)); 
			}
			else { 
				jQuery("#PSvalue").val(CAS.valueOf()); 
			}

			jQuery("#PSvalue_mlt").val('');
		}
	}

	// 20100802 JRD - assign keypress event on PSvalue_mlt to monitor for when there are more
	//		    than 30 cas entered. When there is, display an error message.
	jQuery(".CAScount").each(function() {
		var elClass = jQuery(this).attr('class');
		var maxWords = 30;
		var countControl = elClass.substring((elClass.indexOf('['))+1, elClass.lastIndexOf(']')).split(',');

		if(countControl.length > 1) {
			maxWords = countControl[1];
		} else {
			maxWords = countControl[0];
		}

		jQuery(this).bind('change paste keypress keydown,', function() {
			var number = 0;
			// split based on spaces into an array, count spots in array - gives # of cas's
			// \s is a non-white-space character
			// g means global

			var str  = jQuery(this).val();
			var str1 = jQuery(this).val();

			while (str.substr(0,1) == '\n' || str.substr(0,1) == ' ')
			{
			 	str = str.substr(1);
			}

			//while (str.substr(str.length-1,1) == '\n' || str.substr(str.length-1,1) == ' ')
			//{
			// str = str.substr(0,str.length-1);
			//}

			jQuery(this).val(str);

			var numWords = jQuery.trim($(this).val()).replace(/\s+/g," ").split(' ').length;

			if(numWords > 30) {
				document.getElementById("productSearchButton").disabled=true;
				jQuery("#productSearchButton").hide();
				jQuery("span[key=cas_30]").show();
			} else {
				document.getElementById("productSearchButton").disabled=false;
				jQuery("span[key=cas_30]").hide();
				jQuery("#productSearchButton").show();
			}
			jQuery(this).val(str1);
		});
	});

    
    /**
     * Handle display of input fields for document search. Possibilities are CofA and MSDS.
     */
    jQuery('#docsrchtyp').change(function () {
    	type = jQuery(this).val();
            
        if (type == "MSDS") {
        	jQuery('.COA').css('display', 'none');
            jQuery('.MSDS').css('display', '');
        }
            
        if (type == "COA") {
            jQuery('.COA').css('display', '');
            jQuery('.MSDS').css('display', 'none');
        }
    });
    
        
    /**
     * Handle the document search
     * The click event handler here handles the document search for MSDS and CofA.
     */
    jQuery("#doc_search").click(function (event) {
        event.preventDefault();
         
        type = jQuery('#docsrchtyp').val();
        jQuery("#errmsg span").css('display', 'none');

		/**
		 * MSDS
		 */
        if(type == "MSDS") {
            	
        	var msds_region = jQuery("#MSDSregion").val();
            //DK 20110708: nowhere used in this file
            //var msds_region_txt = jQuery("#MSDSregion option:selected").text();
            var dsstk = jQuery("#product").val();
            
            //DK 20110712 - added to retrieve input from captcha text
            var captchaTxt = jQuery("input[name=inpCaptcha]").val();
			if(captchaTxt == "undefined")
	        {
	        	captchaTxt = "";
	        }
        
            // JEL 20090903
            // force a minimum of 5 character search
            if (dsstk.length >= 5) {

				//if the parent document is done loading display a loading image to indicate we are searching for a MSDS PDF
                if (typeof document.loading === "undefined") {
                	//DK 20110712 - removed <br /><br /> and replaced with nbsp to save space and display it next to the button not beneath it
                	jQuery(this).after("<span id=\"loading\">&nbsp;&nbsp;<img src=\"../images/loadingAnimation.gif\" alt=\"Loading, please wait...\" style=\"vertical-align: super;\" /></span>");
                    //jQuery("#doc_search").css("display", "none");
                    jQuery("#doc_search").attr("disabled", "disabled");
                }
                
                //make sure the message is hidden
                jQuery("#captcha-invalid").addClass("hideit");
                
                jQuery.ajax({
                    type: "GET",
                    url: "GD120W.pgm",
                    dataType: "json",
                    data: "task=getpdf&region=" + msds_region + "&product=" + dsstk + "&inpCaptcha=" + captchaTxt,
                    cache: false,
                    success: function (rtnmsg) {
                      	//if there are no PDFs, build string and message to be output for the user
                        if (rtnmsg.count === 0) {
                            jQuery("#MSDSterm").html(" <b>" + dsstk + "</b> ");
                            jQuery(".MSDSmsg a").attr("href", "gp110w.pgm?item=" + dsstk + "&MSDS=Y")
                            jQuery("span.MSDSmsg").css('display', '');
                            jQuery(".MSDSmsg > span").show();
                            jQuery(".MSDSmsg > a").show();
                            jQuery(".MSDSmsg > a > span").show();
                 
                            jQuery("#loading").remove();
                        } 
                        //if we have more than one MSDS PDF (Region "All" for example)
                        else if (rtnmsg.count > 1) {
                            jQuery("#task").val("default");
                            jQuery("#msds_form").attr({target: "_top", action: "gd120w.pgm"});
                            jQuery("#msds_form").submit();
                        } 
                        //if we have a path, change the target, action and task of the form and submit it again
                        else if (rtnmsg.path) {
                            jQuery("#msds_form").attr({target: "_blank", action: "gd120w.pdf"});

                            jQuery("#task").val("servepdf");
                            jQuery("#msds_form").submit();
                            jQuery("#loading").remove();
                            jQuery("#captcha-image").html("");
                        } 
                        else if (rtnmsg.captcha) {
                        	//DK 20110712 - added if statement to handle captcha instead of cookie
                        	var objHtml = jQuery("#captcha-image").html();
                        	jQuery("#captcha-image").html(rtnmsg.captcha);
							//jQuery("#captcha-invalid").appendTo("#errmsg").removeClass("hideit");

							if(objHtml != "")
							{
                            	jQuery("#captcha-invalid").removeClass("hideit");
                            }
                        	jQuery("#loading").remove();
                        }
                            
                        jQuery("#doc_search").attr("disabled", "");
                        jQuery("#doc_search").removeAttr("disabled");
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        jQuery("#loading").remove();
                        jQuery("#doc_search").attr("disabled", "");
                    }
                });
            } else {                    
                // KAB 20091001 - get hidden error message text
                jQuery('span[key=at_least_five_characters]').css('display', '');
                return false;
            }
        }
        /**
		 * CofA
		 */
        else if (type == "COA") 
        {
            jQuery("#cofa_errmsg").html('');
            jQuery.ajax({
                type: "GET",
                url: "GD130W.pgm",
                data: "task=ajax&itemnum=" + jQuery("#CASproduct").val() + "&lot=" + jQuery('#CASlot').val(),
                dataType: "json",
                cache: false,
                success: function (rtnmsg) {                                                                                
                    if (rtnmsg.error) {                            
                        jQuery("#cofa_errmsg").html(rtnmsg.error).css({"display":""});    
                            
                        // KAB 20091008 - translate returned error message
                        tran_SwitchLang(curLang , "#cofa_errmsg"); 

                    } else if (rtnmsg.count == 0) {
                        jQuery("#term").html(jQuery("#CASproduct").val()+" - "+jQuery('#CASlot').val());

                        // KAB 20091001 - do not remove the errmsg div, just clear it out
                        //jQuery("#errmsg").remove();
                        jQuery("#errmsg").html("&nbsp;");
                            
                    } else if (rtnmsg.path) {
                        jQuery("#cofa_form").attr("action", rtnmsg.path);
                        jQuery("#cofa_form").attr("target", "_blank");
                        jQuery("#cofa_form").submit();
                            
                    } else {
                        jQuery("#cofa_form").attr("action", "gd130w.pgm");
                        jQuery("#cofa_form").attr("target", "_top");
                        jQuery("#cofa_form").submit();
                    }
                        
                }
            });    
        }
            
    });

	// set initial display rules
	if (jQuery('#srchtyp').val() == "CAS") {
		jQuery('#chineseText').hide();
		jQuery('#PSvalue_mlt').show();
		jQuery('#PSvalue').hide();
		jQuery(".limitcas30").show();
	}
	else if (jQuery('#srchtyp').val() == "PROD"){
		jQuery('#PSvalue_mlt').hide();
		jQuery('#PSvalue').show();
		jQuery(".limitcas30").hide();
		if (curLang.toUpperCase() == "ZH") {
			jQuery('#chineseText').show();
		}
		else {
			jQuery('#chineseText').hide();
			
		}
	}
	else {
		jQuery(".limitcas30").hide();
		jQuery('#chineseText').hide();
		jQuery('#PSvalue_mlt').hide();
		jQuery('#PSvalue').show();
	}

	jQuery("#captcha-reload").live('click', function (){
		var container = jQuery(this).parent().parent();

		jQuery.ajax({
			url: "gd120w.pgm",
			data: "task=refreshCpt",
			success: function(rtn){
				//jQuery(container).html("");

				jQuery(container).html(rtn);
				
				tran_SwitchLang(curLang , "#captcha-image");
			}
		});
	});
	
});
