if (ajax == null) var ajax = {};
if (ajax.autocomplete == null) ajax.autocomplete = {};
ajax.autocomplete.currentInputField = null;
ajax.autocomplete.getOptions=function(optionType,inputField) {
    ajax.autocomplete.currentInputField = inputField;
    var box = document.getElementById("auto_box");
    ajax.autocomplete.enableButton(ajax.autocomplete.currentInputField.id, false);
    if(ajax.autocomplete.currentInputField.value.length>2) {
        FormOptionsProvider.getMatchs(optionType,ajax.autocomplete.currentInputField.value,ajax.autocomplete.optionsHandler);
    } else {
       if(box!=null) {
           box.style.display="none";
       }
    }
};

ajax.autocomplete.optionsHandler=function(data){
    var box = document.getElementById("auto_box");
    var html = '<ul style="list-style: none;">';
    var termText=ajax.autocomplete.currentInputField.value.toUpperCase();
    var maxWidth = 0;
    if (data[0]=='true') {
	    ajax.autocomplete.enableButton(ajax.autocomplete.currentInputField.id, true);
    } else {
	    ajax.autocomplete.enableButton(ajax.autocomplete.currentInputField.id, false);
    }
    var datasize = data.length - 1;
    for(var i=1;i<data.length;i++) {
        html+='<li onclick="ajax.autocomplete.selectOption(\'';
        html+=data[i]+'\');">';
        html+='<a href="#" onclick="return false;" style="display: block;padding: 0px">';
        var formatedData = data[i].replace( termText, '<b>'+termText+'</b>');
        html+=formatedData.replace(',', ', ');
        html+='</a></li>';
        var dataLength = (formatedData.length + 1) * 6;
        if (maxWidth < dataLength) {
        	maxWidth = dataLength;
        }
    }
    html+="</ul>";
    if (ajax.autocomplete.currentInputField.offsetWidth > maxWidth) {
    		maxWidth = 	ajax.autocomplete.currentInputField.offsetWidth;
    }
    //alert(html);
    if(box==null) {
        box=ajax.autocomplete.createDiv(data,maxWidth);
    }
    
    box.style.display="block";
    var boxHeight = datasize * 16;
    box.style.width=maxWidth + 'px';

    box.style.top=ajax.autocomplete.getElementY(ajax.autocomplete.currentInputField) +20 +'px';
    box.style.left=ajax.autocomplete.getElementX(ajax.autocomplete.currentInputField) +'px'; 
    if (datasize > 10) {
	    box.style.overflow='auto';
        box.style.height='160px';
    } else {
    	box.style.overflow='';
        box.style.height=boxHeight + 3 + 'px';
    }			
    if (datasize > 0) {
        box.innerHTML=html;
    } else{
        box.innerHTML = "Your location is not recognised. Please re-enter your suburb or postcode";	
        box.style.height='50px';
        box.style.width='150px';
        box.style.color='#cc0000';
    }
     
    box.style.display="block";
};

ajax.autocomplete.validateOption=function(optionType, inputFieldId) {
     FormOptionsProvider.validateOption(optionType,document.getElementById(inputFieldId).value, false, function(data) {
         if (data == true) {
             document.getElementById(inputFieldId).form.submit(); 
         }
     });
     return false;
};
ajax.autocomplete.getSelectFieldOptions=function(optionType,selectFieldId, defaultValue, defaultText) {
	ajax.autocomplete.getSelectFieldOptions(optionType,selectFieldId, defaultValue, defaultText, null);
};
ajax.autocomplete.getSelectFieldOptions=function(optionType,selectFieldId, defaultValue, defaultText, defaultOption) {
	var selectField = document.getElementById(selectFieldId);
	removeAllChildren(selectField);
    FormOptionsProvider.getOptions(optionType, function(data){
    	if (defaultText != null) {
			var div = document.createElement('option'); 	
			div.value=defaultValue;
			div.innerHTML=defaultText;
			if (defaultOption == div.value) {
				div.selected = true;
			}
			selectField.appendChild(div);
		}
		for(var i=0;i<data.length;i++) {	 
			var idAndName=data[i].split('~`');
			if (idAndName[1].toLowerCase()!="all catalogues" && idAndName[1].toLowerCase()!="all retailers") {
				var option = document.createElement('option'); 	
				option.value = idAndName[0];
				option.innerHTML = encodeHtml(idAndName[1]);
				if (defaultOption == option.value) {
					option.selected = true;
				}
				selectField.appendChild(option);
			}
		}
   });
};
ajax.autocomplete.getSubSelectFieldOptions=function(optionType,selectFieldId, matchText, defaultValue, defaultText) {
	var selectField = document.getElementById(selectFieldId);
	removeAllChildren(selectField);
    FormOptionsProvider.getMatchs(optionType, matchText, function(data){
		var div = document.createElement('option'); 	
		div.value=defaultValue;
		div.innerHTML=defaultText;
		selectField.appendChild(div);
		for(var i=0;i<data.length;i++) {	   
			var option = document.createElement('option'); 	
			var idAndName=data[i].split('~`');
			option.value = idAndName[0];
			option.innerHTML = encodeHtml(idAndName[1]);
			selectField.appendChild(option);
		}
   });
};
ajax.autocomplete.selectOption=function(value){
    if ( ajax.autocomplete.currentInputField ) {
        ajax.autocomplete.currentInputField.value=value;
        ajax.autocomplete.enableButton(ajax.autocomplete.currentInputField.id, true);
        ajax.autocomplete.currentInputField.focus();
        //dwr.util.setValue(inputId,value);
        //ajax.autocomplete.currentInputField=null;
    }
    document.getElementById('auto_box').style.display='none';
};
ajax.autocomplete.enableButton=function(id, flag) {
		var setButton=document.getElementById('set'+id);
        if (setButton) {
            setButton.disabled=!flag;
            if (setButton.tagName!='INPUT') {
            	if (flag) {
	                setButton.onclick=ajax.autocomplete.submitForm;
                } else {
	                setButton.onclick="";
                }
            }
        }
}
ajax.autocomplete.getElementY=function(element){
	var targetTop = 0;
	if (element.offsetParent) {
		while (element.offsetParent) {
			targetTop += element.offsetTop;
            element = element.offsetParent;
		}
	} else if (element.y) {
		targetTop += element.y;
    }
	return targetTop;
};
ajax.autocomplete.getElementX=function(element){
	var targetLeft = 0;
	if (element.offsetParent) {
		while (element.offsetParent) {
			targetLeft += element.offsetLeft;
            element = element.offsetParent;
		}
	} else if (element.y) {
		targetLeft += element.x;
    }
	return targetLeft;
};

ajax.autocomplete.createDiv=function(data,width){
    var div = document.createElement('div'); 	
    div.id='auto_box';
    div.style.zIndex="2";
    div.style.position='absolute';
    div.style.border='2px solid #ebebeb';
    //div.style.backgroundColor='#FFFFEE';
    div.style.backgroundColor='#FF0000';
    //div.style.margin='30px 0 0 0';
    document.body.appendChild(div);
    return div;
};
ajax.autocomplete.submitForm=function(){
    ajax.autocomplete.currentInputField.form.submit();
};
ajax.autocomplete.populateOfferDetail=function(data,OfferId,value2) {
   if($("#popupOfferIdVal").html() == OfferId) {
	   if (data != null) { 
	   		var imagePNG = data.split("|~");
	   		if (imagePNG[2].length > 0) {
				$(".popup_offer_title").html(imagePNG[2]);
	   			$(".image_content img").attr('alt',imagePNG[2]);
   			} else {
				$(".popup_offer_title").html("Catalogue Offer");
		   		$(".image_content img").attr('alt',"");	   			
   			}
	   		var embedVideoNode = document.getElementById("embedvideocontainer");
	   		embedVideoNode.innerHTML="";
			if (imagePNG[22].length > 0) {
				$(".image_content img").css("visibility","hidden");
				var videoWidth=198;
				var videoHeight=150;
				var offerVideoLink="http://www.youtube.com/v/"+imagePNG[22];
				embedVideoNode.innerHTML=
					"<object width='"+videoWidth+"' height='"+videoHeight+"'><param name='movie' value='"+offerVideoLink+"'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='"+offerVideoLink+"' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='"+videoWidth+"' height='"+videoHeight+"'></embed></object>";
			} else if (imagePNG[15].length > 0) {
		        $(".image_content img").css("visibility","hidden");
	   			$("#psimage__psimage").attr("src",value2+"empty.bmp");
		        $("#catalogue-popup-enlarge__psimage").html("Play Video");
				$("#catalogue-popup-enlarge__psimage").show();
				embedVideoNode.innerHTML="<div id='normalEmbedobject_psimage'></div>";	  
				setMediaNormalHtml(imagePNG[15],imagePNG[16],imagePNG[17],imagePNG[18],"psimage",imagePNG[19]);
			} else if (imagePNG[3].length > 0) {
	   			$("#psimage__psimage").attr("src",value2+imagePNG[3]);
		        $("#catalogue-popup-enlarge__psimage").html("Enlarge Image");
				$("#catalogue-popup-enlarge__psimage").show();
		        $(".image_content img").css("visibility","visible");				
 	   		} else {
		   		$(".image_content img").css("visibility","hidden");
 	   		}

	   		var detailLink = "";
	   		if (imagePNG[1].length > 0) {
	   			detailLink = imagePNG[1];
	   			if (imagePNG[13] == "more") {
		   			detailLink = detailLink + ' <a href="#" onClick="gotoproductdetails(); return false;" class="blue">more</a>';
	   			}
	   		}
	   		$(".popup_description_info").html(detailLink);
	   		var pricetext = "";
			if (imagePNG[6].length > 0) {
				pricetext = imagePNG[6];
			}
//			if (imagePNG[7].length > 0) {
//				pricetext = pricetext+ " (save "+imagePNG[7]+")";
//			}
			if (pricetext.length >29) {
				pricetext = pricetext.substring(0, 28)+"...";
			}
			if (imagePNG[7].length > 0) {
				$(".catalogue-popup-savings").html("<strong>"+imagePNG[7]+"<strong>");
			} else {
				$(".catalogue-popup-savings").html("");
			}			
//			if (imagePNG[8].length > 0 && imagePNG[8].toLowerCase() == "sold out") {
//				pricetext = pricetext+ " <span style='color:red'>" + imagePNG[8] + "</span>";
//			}
			$("#popup_offer_description .catalogue-popup-price").html("<strong>"+pricetext+"<strong>");
			$(".catalogue-popup-sub-title").html(imagePNG[9]);
			if (imagePNG[10].length > 0) {
				$("#enlarge-location_psimage").attr("value",imagePNG[10]);
			}
			if (imagePNG[11].length > 0 && imagePNG[12].length > 0) {
				$("#enlargeimagelink").attr("href", getRetailerBuyNowLink(imagePNG[12]));
				$("#enlargeimagelink").html(getFixLengthString(imagePNG[11],18));
				$("#enlargeimagelink").attr("target",(imagePNG[21]=="true"?"_blank":"_self"));
				$("#enlargeimagepanel").show();
			}
			if (imagePNG[20].length > 0) {
				$("#catalogue-popup-tandc").show();
				$("#catalogue-popup-tandc-text").html(imagePNG[20]);
			}
	   		$("#OfferIdVal").attr("value",imagePNG[5]);
	   		$("#retailerNameVal").html(imagePNG[14])
			$("#popup_offer_description .popup_offer_detaillink").show();
			appendOfferViewedTracking();
			omCatalogueViewEvent("event7", OfferId, imagePNG[2], imagePNG[14]);
	   	} else {
	   		ajax.autocomplete.clearOfferPopup();
	   		$(".popup_description_info").html('There is no information for this offer');
	   		$(".popup_offer_title").html("Catalogue Offer");
//			$("#popup_offer_description .savings").html("");
	   		$("#OfferIdVal").attr("value","");
	   	}
	}
}
ajax.autocomplete.getOfferDetails=function(OfferId,value2) {
   FormOptionsProvider.getFirstMatch("Offer", OfferId, function(data){
   		popupDataArray[OfferId] = data;
   		ajax.autocomplete.populateOfferDetail(data, OfferId,value2);
   });
};
ajax.autocomplete.clearOfferPopup=function() {
//		$("#psimage__psimage").attr("src",value2+"empty.bmp");
		$(".image_content img").css("visibility","hidden");
   		$(".image_content img").attr('alt',"");
		document.getElementById("embedvideocontainer").innerHTML="";	  
		$(".catalogue-popup-sub-title").html("");
		$("#catalogue-popup-enlarge__psimage").hide();
		$("#catalogue-popup-tandc").hide();
		$(".catalogue-popup-savings").html("");
		$("#popup_offer_description .catalogue-popup-price").html("");
		$("#enlarge-location_psimage").attr("");
}
ajax.autocomplete.resetOfferPopup=function() {
	//Reset or hide fields in the popup
	ajax.autocomplete.clearOfferPopup();
	$(".popup_description_info").html('');
	$(".popup_offer_title").html("");
	$("#popup_offer_description .popup_offer_detaillink").hide();
	$("#retailerNameVal").html("");
	$("#enlargeimagepanel").hide();
}
// Common functions
ajax.callOnLoad=function(load){
  if (window.addEventListener){
    window.addEventListener("load", load, false);
  }
  else if (window.attachEvent) {
    window.attachEvent("onload", load);
  }
  else {
    window.onload = load;
  }
}
ajax.debugFlag=false;
ajax.setDebug=function(flag) {
    ajax.debugFlag=flag;
}
ajax.debug=function(msg) {
    if( ajax.debugFlag ) {
        var div = document.getElementById('LoGmSg');
        if(div==null) {
            div = document.createElement('div');
            div.id='LoGmSg';
            document.body.appendChild(div);
        }
        var oldMsgs = div.innerHTML;
        div.innerHTML = oldMsgs+'<br/>'+msg;
    }
}
// Old version of image resize
//	   			var popupImage = new Image();
//	   			popupImage.name = OfferId;
//	   			objSafariImage.name = OfferId; 
//	   			
//	   			if(popupImageArray[popupImage.name] == null) {
//					popupImage.onload = resizeImage;
//				} else {
//					objImage = popupImageArray[popupImage.name];
//					displayPopupImage(objImage);
//				}
//	   			popupImage.src = value2+imagePNG[3];
//	   			objSafariImage.src = value2+imagePNG[3];