var alreadySubmitted = false;

jQuery.preloadImages = function() {
	for(var i = 0; i<arguments.length; i++) {
		jQuery("<img>").attr("src", arguments[i]);
	}
};

var _global_popup_name = "popup_";

showWait = function() {
  if (jQuery.browser.msie) {
	//correct position (just for IE !)
    $("#please_wait").css("top",document.body.scrollTop);
  }
  $("#please_wait").show();
  $("select").hide();
}; 

hideWait = function() {
  $("select").show();
  $("#please_wait").hide();
};

openPopupFromElement = function(jQueryElt) {
  var href=jQueryElt.attr('href');
  var name=_global_popup_name+jQueryElt.attr('id');
  win = window.open(href, name.replace(/\./g, '__p__'), 'width=625,height=540,resizable=yes,scrollbars=yes,status=yes');
  win.focus();
  return false;
} //end openPopupFromElement

fromComponentValueSelected = function(windowName, value) {
  var _indexOfPopup = windowName.indexOf(_global_popup_name);
  var _indexOfHelper = windowName.indexOf('Helper');

  if(_indexOfPopup==0 && _indexOfHelper>7) {
    var _inputId = windowName.substring(_global_popup_name.length, _indexOfHelper).replace(/__p__/g, '.');
    var _inputElt = $("input[id='"+_inputId+"']");

    _inputElt.val(value).change();
  }
} //end fromComponentValueSelected

openAjaxPopupFromElement = function(jQueryElt) {
  var eltId = jQueryElt.attr('id');
  if(eltId!='' && eltId!='undefined') {

	var ajaxPopupDivId = "ajaxPopupDiv_" + eltId;
    var ajaxPopupDivSelector = "div#"+ajaxPopupDivId;

    if($(ajaxPopupDivSelector).size()==0) {
      jQueryElt.after('<div style="position:absolute;margin:0;"><div id="'+ajaxPopupDivId+'" class="jqmNotice"><div class="jqmnTitle jqDrag"><h1></h1></div><div class="jqmnContent"></div><img src="res/img/png/close.png" alt="" class="jqmClose" /><img src="res/img/png/resize.png" alt="" class="jqResize" /></div></div>');

      var ajaxPopupDivContentSelector = $(ajaxPopupDivSelector + " div.jqmnContent");
      var ajaxPopupDivTitleSelector = ajaxPopupDivSelector + " div.jqmnTitle h1";
      var ajaxPopupClose = $(ajaxPopupDivSelector + " .jqmClose");

	  	$(ajaxPopupDivSelector).jqDrag(".jqDrag").jqResize(".jqResize").jqmAddClose(ajaxPopupClose).jqm({
	  	    ajax: "@href",
	  	    target: ajaxPopupDivContentSelector,
	  	    overlay: 85,
	  	    onShow: function(h) {
	  			$(ajaxPopupDivTitleSelector).text($(h.t).attr('title'));
	  	        h.w.css('opacity',0.85).slideDown();
	  	    },
	  	    onHide: function(h) {
	  	        h.w.hide(function() { if(h.o) h.o.remove(); }); 
	  	    }
	  	});

	  	$(ajaxPopupDivSelector).jqmAddTrigger(jQueryElt);
	  	
	  	jQueryElt.click();
    }

	return false;
  }
} //end openAjaxPopupFromElement

updateDescription = function(uri, labelSpan) {
	if(labelSpan) {
		$.get(uri, function(data){
			labelSpan.html(data);
		});
	}
}

refreshCustomSite = function(jQueryElt) {
	if(jQueryElt) {
		var labelSpan = $("#"+jQueryElt.attr('id')+"Span");
		var id = jQueryElt.val();
		if (id != "" ) {
			var uri = "customerSiteSearch.do?customSiteId="+id;
			updateDescription(uri, labelSpan);
		}
		else {
			labelSpan.html("");
		}
	}
}

refreshParty = function(jQueryElt) {
	if(jQueryElt) {
		var labelSpan = $("#"+jQueryElt.attr('id')+"Span");
		var id = jQueryElt.val();
		if (id != "" ) {
			var uri = "description.do?type=party&partyId="+id;
			updateDescription(uri, labelSpan);
		}
		else {
			labelSpan.html("");
		}
	}
}


refreshCity = function(jQueryElt) {
	if(jQueryElt) {
		var cityId = jQueryElt.attr('id')
		var placeId = cityId.substr(0, cityId.length - 5)
		refreshPlace(placeId);
	}
}

refreshCountry = function(jQueryElt) {
	if(jQueryElt) {
		var countryId = jQueryElt.attr('id')
		var placeId = countryId.substr(0, countryId.length - 8)
		refreshPlace(placeId);
	}
}

refreshPlace = function(placeId) {
	if(placeId) {
		var cityCode = $("#" + placeId + "_city").val();;
		var countryCode = $("#" + placeId + "_country").val();
		var countrySpan = $("#" + placeId + "_countrySpan");
		var citySpan = $("#" + placeId + "_citySpan");
		if(countryCode != "") {
			var uri = "description.do?type=country&countryCode="+countryCode;
			updateDescription(uri, countrySpan);
			if(cityCode != "") {
				var uri = "description.do?type=city&countryCode="+countryCode+"&cityCode="+cityCode;
				updateDescription(uri, citySpan);
			} else {
				citySpan.html("");
			}
		} else {
			countrySpan.html("");
		}
	}
}

refreshProjectId = function(jQueryElt) {
	if(jQueryElt) {
		var labelSpan = $("#"+jQueryElt.attr('id')+"Span");
		var projectId = jQueryElt.val();
		if(projectId != "") {
			var uri = "description.do?type=project&projectId="+projectId;
			updateDescription(uri, labelSpan);
		}
		else {
			labelSpan.html("")
		}
	}
}

refreshRiskFunctionId = function(jQueryElt) {
	if(jQueryElt) {
		var labelSpan = $("#"+jQueryElt.attr('id')+"Span");
		var riskFunctionId = jQueryElt.val();
		if(riskFunctionId != "") {
			var uri = "description.do?type=riskFunction&riskFunctionId="+riskFunctionId;
			updateDescription(uri, labelSpan);
		}
		else {
			labelSpan.html("")
		}
	}
}


/*
findPos = function (obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
    }
    return {x:curleft,y:curtop};
}
*/

jQuery(function($) {

	//If there is only one form in the page, 
	//set the focus to the first input of this form...
	if($("form").length==1) {
		$("form input:first").focus();
	}

	//For all forms, show wait message when submit... 
	$("form").submit(function() {
		if(!alreadySubmitted) {
			alreadySubmitted = true;
			showWait();
		} else {
			return false;
		}
	});

	$("a.codeHelper").click(function() {
      return openPopupFromElement($(this));
    });

	$("a.popup").click(function() {
	  return openPopupFromElement($(this));
	});

  $(document).on("click", "a.link_detail", function() {
    return openPopupFromElement($(this));
  });

$(document).on("click", ".codeHelperDescription a", function() {
    return openPopupFromElement($(this));
  });

	$("select#pagesize").change(function() {
		var uri = $(this).attr("class")+"?"+$(this).serialize();
		showWait();
		window.location=uri;
	});

	$(document).bind('keydown', 'F1', function(event) {
		return openPopupFromElement($("a#link_help"));
    });

	$("a.ajaxPopup").click(function() {
	  return openAjaxPopupFromElement($(this));
	});

	$("input[type='checkbox'].selectAll").each(function() {
		var idSelectAll = $(this).attr('id');
		if(idSelectAll.indexOf("_")>0) {
			var idSelectOne = idSelectAll.substring(0, idSelectAll.indexOf("_"));
			$("input[name="+idSelectOne+"]").click(function() {
				var checkedAll = true;
				$("input[name="+idSelectOne+"]").each(function() {checkedAll = checkedAll && this.checked});
				$("#"+idSelectAll).attr('checked', checkedAll); 
			});
		}
	}).click(function() {
		var idSelectAll = $(this).attr('id');
		if(idSelectAll.indexOf("_")>0) {
			var checked_status = this.checked;
			var idSelectOne = idSelectAll.substring(0, idSelectAll.indexOf("_"));
			$("input[name="+idSelectOne+"]").each(function() {
				this.checked = checked_status;
			});
		}
	});
	
	$("input.input_customerComponentClass").change(function() {
		refreshCustomSite($(this));
	}).each(function() {
		refreshCustomSite($(this));
	});

	$("input.input_externalOrganizationComponentClass").change(function() {
		refreshParty($(this));
	}).each(function() {
		refreshParty($(this));
	});

	
	$("input.input_city_PlaceComponent").change(function() {
		refreshCity($(this));
	}).each(function() {
		refreshCity($(this));
	});
	
	$("input.input_country_PlaceComponent").change(function() {
		refreshCountry($(this));
	});
	
	$("input.input_projectIdComponentClass").change(function() {
		refreshProjectId($(this));
	}).each(function() {
		refreshProjectId($(this));
	});
	
	$("input.input_riskFunctionIdComponentClass").change(function() {
		refreshRiskFunctionId($(this));
	}).each(function() {
		refreshRiskFunctionId($(this));
	});

});