$(function() {
	/**######################## Resisable textarea ########################*/
	$('textarea.resizable:not(.processed)').TextAreaResizer();
	$(".grippie").css({"width":"302px"});
	
	/**################## Handling personal details window ####################*/
	/** Set position string depending on browser (IE6 doesn't have position:fixed) */
    var positionString = 'fixed';
    if($.browser.className=='msie6') positionString = 'absolute';

    /** Calculate position and style the popup window */
    var personalDetailsElement =  $("#personalDetailsWindow");
    var mainWindowElement = $(window);

	var personalDetailsElementWidth = 500;
//	var personalDetailsElementWidth = personalDetailsElement.width();//<== This doesn't work on Firefox very well...
	
    var leftPosition = Math.floor((mainWindowElement.width() - personalDetailsElementWidth)/2);  
    var topPosition  = Math.floor((mainWindowElement.height() - personalDetailsElement.height())/2);
    personalDetailsElement.css({  
                            "position": positionString,
                            "top": topPosition,  
                            "left": leftPosition,
                            "width": "500px",
                            "padding": "0px"
                         })
                    .draggable();
                    
	$("a[rel^='lightbox']").lightBox({
								overlayBgColor: '#000',
								overlayOpacity: '0.8'
							});

    /**################## Open personal details window ##########################*/
	$(".contact_form-submit-med").attr("style", "cursor:pointer;")
								 .click(function(){
	                             displayOverlay();
											        if(personalDetailsElement.is(":hidden"))
											        {
											        	personalDetailsElement.fadeIn("normal");
											        }
								 				});
    function displayOverlay()
    {
        var height = $('body:first').height();
        var width = document.documentElement.clientWidth;
        $('#overlay').height(height)
                     .width(width)
                     .show()
                     .fadeTo(400, 0.7, function(){
                     							 });     
    }

	/**##################### Handle Item Remove Button #############################*/
	$("img[id^='removeFromList_']").attr("style", "cursor:pointer;")
							 	   .click(function(){
												var compIdRetrieved = $(this).attr("id").substr(15);
//alert(compIdRetrieved);
												$("#amount_" + compIdRetrieved.replace(",", "\\,")).val(0);
												handleQtyChanged(compIdRetrieved, 0);
							 				});
							
	/**##################### Handle quantity changed #############################*/
	var amountExisting = 0;
	$("input[id^='amount_']").focus(function(){
												amountExisting = $(this).val();
											})
							 .blur(function(){
												var validate = new Validate();
												if(!validate.isNum($(this).val()))
												{
													$(this).val(amountExisting);
												}
												else
												{
													handleQtyChanged($(this).attr("id").substr(7), $(this).val());										
												}
									  		});
	function handleQtyChanged(comIdName, qtyEntered)
	{
		if(!isNaN(qtyEntered))
		{
			/* Get processing image object and show it */
			var proImg = $("#processingImage_"+comIdName);
			proImg.show();
	
			/* Get result box object */
//			var resultBox = $("#result");
	
			/* serialize form */
			param = 'comId='+comIdName+'&quantity='+qtyEntered;

			/* ajax */
			$.ajax({
				type: "POST",
				url: "/include/product_addDeleteItem.php",
				data: param,
				dataType: "json",
				success: function(data)
				{
					if(data.result==true)
					{
						if(qtyEntered==0)
						{
							$("#productItemBox_" + comIdName.replace(",", "\\,")).fadeOut("slow");
							handleContinueButton();
						}	
					}
					else
					{

					}
				},
				complete: function(xhr, myStatus)
				{
					/* Hide processing image */
					proImg.hide();
				}
			});			
		}
		else
		{

		}
	}
	function handleContinueButton()
	{
		var totalAmount = 0;
		$("input[id^='amount_']").each(function(){
													totalAmount = parseInt(totalAmount) + parseInt($(this).val());
												});
		if(totalAmount==0)
		{
			$("#contact_form-submit-med").fadeOut("fast");
		}
	}
										  		
    /**################## Close personal details Window #########################*/
    $("#personalDetailsWindowCloseButton").attr("style", "cursor:pointer;")
                              			  .bind("click", handleClosePersonalDetailsWindow);
                                                
 	function handleClosePersonalDetailsWindow()
 	{
        if(personalDetailsElement.is(":visible")) personalDetailsElement.fadeOut("fast");
        $('#overlay').fadeOut("fast");
        $("#submitDetailsSuccessBox").hide();
        $("#contact-us-form").show();
        $("#formMessage").empty();
 	}    
    
    /**################### Submit form ############################*/
    $("#submitPersonalDetailsButton").attr("style", "cursor:pointer;")
                               		 .click(function(){
                                                    submitPersonalDetailsForm();
                                                });
    function submitPersonalDetailsForm()
    {
        /* Get processing image object and show it */
        var proImg = $("#processingImage");
        proImg.show();

        /* Get submit button object */
        var submitButton = $("#submitPersonalDetailsButton");

        /* disable submit button */
        submitButton.attr('disabled', 'disabled');
        
        /* serialize form */
        param = $("#contact-us-form").serialize();
//alert(param);
        /* ajax */
        $.ajax({
            type: "post",
            url: "/include/submitPersonalDetails.php",
            data: param,
            dataType: "json",
            success: function(dataReceived, textStatus)
            {
                if(dataReceived.result==true)
                {
//                  $("#formMessage").empty().append(dataReceived.message);
//alert('true');
                    $("#contact-us-form").fadeOut("fast");
                    $("#submitDetailsSuccessBox").fadeIn("slow");
    				$("#personalDetailsWindowCloseButton").attr("style", "cursor:pointer;")
                              			  				  .unbind("click", handleClosePersonalDetailsWindow)
                              			  				  .click(function(){
														        location.href='index.php';
			                                                });
					$("#continueBrowsingButton").attr("style", "cursor:pointer;")
												.click(function(){
														        location.href='product_list.php';
			                                                });
                }
                else
                {
//alert('false');
                    $("#formMessage").empty().append(dataReceived.message);
                }
                submitButton.removeAttr('disabled');
            },
            complete: function(xhr, myStatus)
            {
                /* Hide processing image */
                proImg.hide();
            }
        });
    } 
    
    /**################### Country Selection ############################*/
    var selectedValue = $("select[name='country'] option:selected").val();
    checkCountrySelected(selectedValue);
    
    $("select[name='country']").change(function(ev){
                                                    	selectedValue = ev.target.value;
                                                        checkCountrySelected(selectedValue);
                                                    });
    function checkCountrySelected(countryIdSelected)
    {
    	if(countryIdSelected==16)
    		$("#stateBox").fadeIn("fast");
		else
			$("#stateBox").fadeOut("slow");
    }
});
