/**
Basis
*/

/** to do on start up */
$(document).ready(function(){
	initTopNavigation();

	handleSelectBoxesOnDetailviewForVariationOnly();
	handleSelectBoxesOnDetailviewForVariationAndPromoItem();

	clearInputFieldOnFocus('input#searchField', -1);
	clearInputFieldOnFocus('input#homepageNewsletter', -1);
	clearInputFieldOnFocus('input#homepageDirectOrder', -1);
	clearInputFieldOnFocus('input#basketDirectOrder', -1);		
	clearInputFieldOnFocus('input#basketAdvantage', 3);		
	clearInputFieldOnFocus('input#basketAdvantage6', 6);		
	
});
 

/** Trigger InputFields to clear on Focus 
 *
 */
function clearInputFieldOnFocus(field, maxLen) {
	eval( 'size =  $("' + field + ':visible").size()');
	if ( size > 0 ) {
		eval( '$("' + field + '").toggleDefaultValue("' + maxLen + '") ');
	}
}


/** Custom Plugins 
		example:  $("#selector").realOffsetTop()
*/
$.fn.realOffsetTop = function() {
  var elem = $(this).get(0)
  var realOffset = elem.offsetTop;
	while (elem.offsetParent) {
		elem = elem.offsetParent
   	realOffset += elem.offsetTop
	}
  return realOffset;
}

/**	toggle default value of input field 
		example to place in $(document).ready(): 
		$('input#searchValue').toggleDefaultValue();
*/
$.fn.toggleDefaultValue = function(maxLen, default_value) {
	var defval = default_value || $(this)[0].defaultValue;
	$(this).focus( function() {
		if (maxLen > 0) {
			$(this).attr("maxlength", maxLen);
		}
		if (this.value == defval) {
		  this.value = "";	
		}
	});	
	$(this).blur( function() {
		$(this).attr("maxlength", 50);
		if (this.value.replace(/\s/, "") == "") {
			this.value = defval; 
		} 
	});
}


/** Popups */
function popup( url, optionen, popupName ) {
      popupWindow = window.open( url, popupName, optionen );
      if ( popupWindow ) {
          if (popupWindow.focus) popupWindow.focus();
          //if (!popupWindow.opener) popupWindow.opener = self; 
      }
      return false;
}

function defaultPopup( url, name ) {
  popup( url, 'width=550,height=350,toolbar=0,menubar=0,resizable=1,scrollbars=1,status=1,left=200,top=10', name );
  return false;
}

function sizePopup(url, name, width, height, top, left ) {
  popup(url, 'width='+width+',height='+height+',toolbar=0,menubar=0,resizable=1,scrollbars=1,status=1,left='+left+',top='+top+'', name );
}

function printPopup( url, name ) {
  popup( url, 'width=755,height=755,toolbar=0,menubar=0,resizable=1,scrollbars=1,status=1,left=200,top=10', name );
}



/** helpers */
function isIE() {
	return $.browser.msie;
} 


/* trigger top navigation */
function initTopNavigation() {
	lis = $("#topNav > ul > li:not(.separator)");
	
  	for (i = 0; i < lis.length; i++ ) {				 
		lis[i].onmouseover = function() {
			setMenuBackground($(this).children("a.m"));
			setDisplayStyleOfTopNavigationLayer(this, 'block');
    	}
		lis[i].onmouseout = function() {
			resetMenuBackground($(this).children("a.m"));
			setDisplayStyleOfTopNavigationLayer(this, 'none'); 
  		}							 
	}
} 

function setDisplayStyleOfTopNavigationLayer( elem, action ) {
	if ( elem.getElementsByTagName("UL").length > 0 ) {
		elem.getElementsByTagName("UL")[0].style.display = action;
	}	
}

function setMenuBackground(elem) {
	menu = getMenuParentLI(elem);
	intOfMenuID = getIntOfMenuID(menu);
	$("#s"+intOfMenuID).addClass("active");
	$("#s"+ (intOfMenuID-1)).addClass("active");			 
	$(menu).addClass("active");	
}
function resetMenuBackground(elem) {
	menu = getMenuParentLI(elem);
	intOfMenuID = getIntOfMenuID(menu);
	$("#s"+intOfMenuID).removeClass("active");
	$("#s"+ (intOfMenuID-1)).removeClass("active");			 
	$(menu).removeClass("active");	
}

function getMenuParentLI(elem) {
	return $(elem).parent()[0];
}
function getIntOfMenuID(menu) {
	return menu.id.substring(1,menu.id.length);
}
/* END topNavigation */


// AJAX cityLookup BEGINN
function getCityByPostalCode(postalCode) {
  if (null != postalCode && "" != postalCode) {
    $.ajax({
        	url: "_/postalCode/" + postalCode + "/lookupCity.html",
            dataType: 'json',
            error: function(msg1, msg2, msg3) {},
            success: function(data) {
              	if(data.cityList.length > 1){
              	//get the old city 
              	var origCity = "";
              	try { 
              		origCity = document.getElementById("city").value;
              		$("#citySelect").addClass(origCity);
              	} catch(err) { 
              		origCity = $("#citySelect").attr("class");
              	}
              	$("#citySelect").html('<select tabindex="7" id="cityDropList" name="city" size="1" onChange="updateCityInClazz(this)"></select>');
			    cityListDropList = document.getElementById("cityDropList");
						    $.each(data.cityList, function(i,item) {
				                 var cityItem = document.createElement("option");
							     cityItem.text = item;
							     cityItem.value = item;
							     if(origCity != '' && origCity == item){
								     cityItem.selected = 'true';
							     }
								 try {
							        cityListDropList.add(cityItem, null);										
								 }
								 catch(ex) {
							        cityListDropList.add(cityItem); // IE only
								 }										 
				        });
              }else if(data.cityList.length == 1){
            	$("#citySelect").html('<input tabindex="7" type="text" name="city" id="city" class="text <@common.err/>"  value="' + data.cityList[0] +'"/>');
              }
            }
    });
  }
}

function updateCityInClazz(selectBox){
	$("#citySelect").removeClass();
	$("#citySelect").addClass(selectBox.value);
}
// AJAX cityLookup END

// Zoom Popup
function zoomPopup( url, name ) {
  popup( url, 'width=525,height=550,toolbar=0,menubar=0,resizable=1,scrollbars=1,status=1,left=200,top=10', name );
  return false;
}


// change select boxes on detailview if variations are sold out
function handleSelectBoxesOnDetailviewForVariationOnly() {
	if ( $("div.detailview").size() > 0 && $("#promoitem_id").size() == 0 ) {
		if ( $("#variation_id > option").size() == 1 ) {
				if ( $("#variation_id > option")[0].value == "" ) {
					// button into basekt etc.
					hideBasketContainerOnDetailview();
					hideAllSelectBoxesAndLabelsOnDetailview();											
				}
		 }
	}
}

function hideAllSelectBoxesAndLabelsOnDetailview() {
	$(".bordure").html("<br><strong>Artikel ist leider ausverkauft!</strong><br><br>");
}

function hideBasketContainerOnDetailview() {
	$("div.basket").hide();	
	if ($("#productNotSpecified").size() == 1) {
		$("#productNotSpecified").hide();	
	}
}

function showBasketContainerOnDetailview() {
	$("div.basket").show();	
}

function 	handleSelectBoxesOnDetailviewForVariationAndPromoItem() {
	if ( $("div.detailview").size() > 0 && $("#promoitem_id").size() > 0  && $("#variation_id").size() > 0 )	{
		if ( $("#variation_id > option").size() == 1 ) {
				if ( $("#variation_id > option")[0].value == "" ) {
					option = $("#variation_id > option")[0];
					option.innerHTML = "ausverkauft";
					hideBasketContainerOnDetailview();					
				}
		 }
	}
}


/* resize iFrame from FactFinder */
function setFrameHeight(h) {
	if (document.all) {
		document.all.search_result.style.height = h;
	} 
	else if (!document.all) {
 		document.getElementById("search_result").height = h;
  	}
}
