/**
 *
 */

function selectAll(state) {
	var i,boxes;

	boxes=document.getElementsByName("item[]");

	for (i=0; i<boxes.length; i++)
		boxes[i].checked=state;

	boxes=document.getElementsByName("cat");

	for (i=0; i<boxes.length; i++)
		boxes[i].checked=state;

	onCartPressed(0);
}

/**
 *
 */

function onSelectAllClicked() {
	selectAll(true);
	updateItemCount();
}

/**
 *
 */

function onSelectNoneClicked() {
	selectAll(false);
	updateItemCount();
}

/**
 *
 */

function onCatLabelClicked(cat) {
	var el=document.getElementById("catdiv_"+cat);

	if (el.style.display=="none")
		el.style.display="block";

	else
		el.style.display="none";

	return false;
}

/**
 *
 */

function onAllClicked(itemIds) {
	var i,all;

	all=true;

	for (i=0; i<itemIds.length; i++) {
		var itemEl=document.getElementById("pitem_"+itemIds[i]);
		all&=itemEl.checked;
	}

	for (i=0; i<itemIds.length; i++) {
		var itemEl=document.getElementById("pitem_"+itemIds[i]);
		itemEl.checked=!all;
	}

	updateItemCount();
}

/**
 *
 */
function storeSearchZoomOut() {
	trace("zoom out..");
	searchMap.setZoom(searchMap.getZoom()-1);
	onUpdateAreaByMapClicked();
	infoEl=document.getElementById("map_moved_info");
	infoEl.style.display="none";
}

/**
 *
 */
function storeSearchZoomIn() {
	trace("zoom in..");
	searchMap.setZoom(searchMap.getZoom()+1);
	onUpdateAreaByMapClicked();
	infoEl=document.getElementById("map_moved_info");
	infoEl.style.display="none";
}

/**
 *
 */
function onItemClicked(itemId) {
	onCartPressed(0);
	updateItemCount();
}

/**
 *
 */

function updateItemCount() {
	var countEl=document.getElementById("item_count");

	var items=document.getElementsByName("item[]");
	var i,totItems=0;
	var itemEl;

	for (i=0; i<items.length; i++) {
		itemEl=items[i];

		if (itemEl.checked)
			totItems++;
	}

	countEl.innerHTML=totItems;
}

/**
 *
 */

function getBaseIcon() {
	var baseIcon = new GIcon(G_DEFAULT_ICON);

	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(27, 31);
	baseIcon.iconAnchor = new GPoint(7, 30);
	baseIcon.shadowSize = new GSize(27, 31);

	return baseIcon;
}

/**
 *
 */

function resetResultColors() {
	var i,els;

	els=document.getElementsByName("store_result");

	for (i=0; i<els.length; i++) {
		var el=els[i];

		el.style.background="#ffffff";
	}
}

function createStoreMarker(store,baseIcon) {
	var latLng=new GLatLng(store.lat,store.lng);

	var storeIcon=new GIcon(baseIcon);

	storeIcon.image=store.markerIcon;

	var markerOptions={icon:storeIcon};
	var marker=new GMarker(latLng, markerOptions);

	return marker;
}

/**
 *
 */

function placeLocations(map,resultStores) {
	var i;

	for (i=resultStores.length-1; i>=0; i--) {
		var result=resultStores[i];

		map.addOverlay(createStoreMarker(result,getBaseIcon()));
	}
}

/**
 *
 */
function onMapMoved() {
	infoEl=document.getElementById("map_moved_info");
	infoEl.style.display="block";

	trace("map moved..");
}

/**
 *
 */
function onCloseMapMovedInfo() {
	infoEl=document.getElementById("map_moved_info");
	infoEl.style.display="none";
}

/**
 *
 */
function onUpdateAreaByMapClicked() {
	var newBounds=searchMap.getBounds();
	var el=document.getElementById("baseUrl");
	var baseUrl=el.value;
	var location=
		baseUrl+searchUrlOnZoom+newBounds.getSouthWest().toUrlValue()+","+newBounds.getNorthEast().toUrlValue();

	window.location=location;
}

/**
 *
 */
function initSearchMap(mapData, resultStores) {
	searchMap=new google.maps.Map2(document.getElementById("google_map"));

	var bounds=new GLatLngBounds(
		new GLatLng(mapData.minLat,mapData.minLng),
		new GLatLng(mapData.maxLat,mapData.maxLng));

	searchMap.setCenter(
		new google.maps.LatLng(mapData.lat,mapData.lng), 
		searchMap.getBoundsZoomLevel(bounds));

	searchMap.addControl(new GLargeMapControl());

	var polygon = new GPolygon([
			new GLatLng(mapData.minLat,mapData.minLng),
			new GLatLng(mapData.maxLat,mapData.minLng),
			new GLatLng(mapData.maxLat,mapData.maxLng),
			new GLatLng(mapData.minLat,mapData.maxLng),
			new GLatLng(mapData.minLat,mapData.minLng)
		], "#808080", 5, 0.3, "#ffffff", 0);
	searchMap.addOverlay(polygon);

	placeLocations(searchMap, resultStores);

	GEvent.addListener(searchMap, "moveend", onMapMoved);
}

/**
 *
 */
function initStoreMap(storeLocation) {
	googleApiLoaded=true;

	var map = new google.maps.Map2(document.getElementById("google_map"));
	var latLng=new google.maps.LatLng(storeLocation.lat,storeLocation.lng)

	map.setCenter(latLng,14);
	map.addControl(new GLargeMapControl());

	var icon=new GIcon(getBaseIcon());
	icon.image="img/markers/butik.png";
	var markerOptions={icon:icon};

	map.addOverlay(new GMarker(latLng, markerOptions));
}

/**
 *
 */

function onContentsClicked() {
/*	var contents=document.getElementById("contents");

	trace("contents: "+contents);

	var popupEl=document.getElementById("cart_content_popup");
	popupEl.style.display="none";

	if (contents.style.display=="none") {
		contents.style.display="block";
	}

	else {
		contents.style.display="none";
	}

	return false;*/
}


/**
 *
 */

function onTabSel(currentTab) {
	var allTabs=["shops","places"];
	var i,tab,tabEl;

	var visibility={
		shops: {
			form_part_location: "block",
			form_part_region: "none"
		},

		places: {
			form_part_location: "none",
			form_part_region: "block"
		}
	};

	for (i=0; i<allTabs.length; i++) {
		tab=allTabs[i];
		tabEl=document.getElementById("tab_"+tab);

		if (tabEl!=null) {
			if (tab==currentTab)
				tabEl.style.backgroundImage="url(img/tab_sel.gif)";

			else
				tabEl.style.backgroundImage="url(img/tab_unsel.gif)";
		}
	}

	var vis=visibility[currentTab];
	var part;

	for (part in vis) {
		var el=document.getElementById(part);

		if (el!=null)
			el.style.display=vis[part];
	}

	document.getElementById("searchType").value=currentTab;

	return false;
}

/**
 *
 */

function showCartContents(event) {
	var windowSize,scroll;
	var popupEl=document.getElementById("cart_content_popup");

	if (popupEl.style.display=="block") {
		hideCartContents();
	}

	else {
		var contents=document.getElementById("cartContents");

		if (contents)
			contents.style.display="none";

		hideCartContents();

		var popupSize=290;

		var xPos=event.clientX;
		var yPos=event.clientY;

		windowSize=getWindowSize();

		if (xPos>windowSize[0]-popupSize) xPos-=popupSize;
		if (xPos<0) xPos=0;

		if (yPos>windowSize[1]-popupSize) yPos-=popupSize;
		if (yPos<0) yPos=0;

		scroll=getPageScroll();
		//alert("scroll: "+scroll[0]+","+scroll[1]);

		popupEl.style.left=scroll[0]+xPos+"px";
		popupEl.style.top=scroll[1]+yPos+"px";
		popupEl.style.display="block";
	}

	return false;
}

/**
 *
 */

function hideCartContents() {
	var popupEl=document.getElementById("cart_content_popup");

	popupEl.style.display="none";
	popupEl.style.left=0;
	popupEl.style.top=0;

	return false;
}

/**
 *
 */

function searchDoneForSubmit(latLng, formId, hiddenId) {
	var s;

	if (!latLng) {
		s="";
	} 

	else {
		s=latLng.toUrlValue();
	}

	document.getElementById(hiddenId).value=s;

	var formEl=document.getElementById(formId);
	formEl.submit();
}

/**
 *
 */
function onSearchPressed(formId, inputId, hiddenId) {
	trace("on search pressed..");

	var textEl=document.getElementById(inputId);
	var s;

	var geocoder=new GClientGeocoder();
	geocoder.setBaseCountryCode("se");

	if (textEl.value.length>0)
		s=textEl.value+", Sweden";

	else
		s="";

	geocoder.getLatLng(s,
		function(latLng) {
			searchDoneForSubmit(latLng, formId, hiddenId);
		});
}

/**
 *
 */
function onFarmshopKeywordSelected() {
	document.getElementById("selectfarmshopkeywords").submit();
}

/**
 *
 */
/*function onAllFarmshopKeywordsClicked() {
	var els=document.getElementsByName("keywords[]");
	var all=true;
	var i;

	for (i=0; i<els.length; i++)
		if (!els[i].checked)
			all=false;

	all=!all;

	for (i=0; i<els.length; i++)
		els[i].checked=all;
}*/

/**
 *
 */
function onSearchFormSubmit() {
	onSearchPressed("mainsearch","main_search_input","search_lat_lng");
	return false;
}

/**
 *
 */
function onFarmshopSearchFormSubmit() {
	onSearchPressed("farmshopsearch","farmshop_search_input","farmshop_lat_lng");
	return false;
}

/**
 *
 */
function updateRatingStars(id, val, prefix) {
	var i;
	var imgFull="img/star-full-"+prefix+".png";
	var imgEmpty="img/star-empty-"+prefix+".png";

	document.getElementById(id).value=val;
	val=parseInt(val);

	for (i=1; i<=5; i++) {
		var el=document.getElementById(id+"_"+i);

		if (i<=val)
			el.src=imgFull;

		else
			el.src=imgEmpty;
	}
}

/**
 *
 */
function setClass(el, className) {
	el.setAttribute("class", className);
	el.setAttribute("className", className); 
}

/**
 *
 */

function onCartPressed(cart) {
/*	var all=document.getElementsByName("cart");
	var i;

	for (i=0; i<all.length; i++)
		setClass(all[i],"themed button");

	var el=document.getElementById("cart_"+cart);

	setClass(el,"themed_active button");

	if (cart==0)
		document.getElementById("contents").style.display="block";

	else {
		var allItems=document.getElementsByName("item[]");

		for (i=0; i<allItems.length; i++)
			allItems[i].checked=false;

		var currentIds=cartItems[cart];

		for (i=0; i<currentIds.length; i++) {
			var itemEl=document.getElementById("item_"+currentIds[i]);
			itemEl.checked=true;
		}

		updateItemCount();
	}

	document.getElementById("cartid").value=cart;*/
}

/**
 *
 */

function initCart(cartid) {
	if (cartid==0) {
		setClass(document.getElementById("cart_"+cartid),
			"themed_active button");

		document.getElementById("cartid").value=cartid;
		updateItemCount();
	}

	else
		onCartPressed(cartid);
}

/**
 *
 */

function popupnoscroll(url, name, width, height) {
	w=window.open(url, name, 'width='+width+',height='+height+
		',resizable=no,scrollbars=no,directories=no,menubar=no'+
		',taskbar=no,toolbar=no');

	w.focus();
}

/**
 *
 */

function multiAllClicked(selectorId, itemName) {
	var selectorEl=document.getElementById(selectorId);
	var itemEls=document.getElementsByName(itemName);
	var i;

	for (i=0; i<itemEls.length; i++) {
		var itemEl=itemEls[i];

		itemEl.checked=selectorEl.checked;
	}
}

/**
 *
 */

function multiItemClicked(selectorId, itemName) {
	var selectorEl=document.getElementById(selectorId);
	var itemEls=document.getElementsByName(itemName);
	var i;
	var all=true;

	for (i=0; i<itemEls.length; i++) {
		var itemEl=itemEls[i];
		all&=itemEl.checked;
	}

	selectorEl.checked=all;
}

/**
 *
 */

function trace(s) {
	if (window.console) {
		console.log(s);
	}
}

/**
 *
 */
function enableButton(anchorId, callback) {
	var anchor=document.getElementById(anchorId);

	anchor.style.color="#404040";
	anchor.href="javascript:void(0);";
	anchor.onclick=callback;
}

/**
 *
 */
function enableInput(inputId) {
	var input=document.getElementById(inputId);

	input.style.backgroundColor="#ffffff";
}

/**
 *
 */
function contains(a, obj) {
	var i = a.length;
	while (i--) {
		if (a[i] == obj) {
			return true;
		}
	}
	return false;
}

/**
 *
 */
function initSurveyForm() {
	var i,id,el,hinder,value;

	for (i=0; i<allProductIds.length; i++) {
		id="price_"+allProductIds[i];
		el=document.getElementById(id);
		value=el.value;
		el.value="";

		hinter=new TextInputHinter(el,value);
		el.hinter=hinter;
		el.disabled=false;
	}

	for (i in priceEntries) {
		id="price_"+i;
		el=document.getElementById(id);
		el.hinter.setValue(priceEntries[i]);
	}
}

/**
 *
 */
function pageLoaded() {
	fixIePng();

	/**** Init main search. ****/
	if (document.getElementById("hasMainSearch")) {
		searchUrlOnZoom="butiksok-i-omrade/";

		placeSuggestor=new Suggestor("main_search_input","main_search_complete",GoogleGeoSuggestions);
		enableInput("main_search_input");
		enableButton("main_search_button",
			function() {
				onSearchPressed("mainsearch","main_search_input","search_lat_lng");
			});
	}

	/**** Init farmshop search. ****/
	if (document.getElementById("hasFarmshopSearch")) {
		searchUrlOnZoom="gardsbutiksok-i-omrade/";

		farmshopSuggestor=new Suggestor("farmshop_search_input","farmshop_search_complete",GoogleGeoSuggestions);
		enableInput("farmshop_search_input");
		enableButton("farmshop_search_button",
			function() {
				onSearchPressed("farmshopsearch","farmshop_search_input","farmshop_lat_lng");
			});
	}

	/**** Init search map. ****/
	if (document.getElementById("hasSearchMap")) {
		initSearchMap(mapData,resultStores);
	}

	/**** Init store map. ****/
	if (document.getElementById("hasStoreMap")) {
		initStoreMap(storeInfo);
	}

	/**** Init survey form. ****/
	if (document.getElementById("haveSurveyProducts")) {
		initSurveyForm();
	}

	/**** Init recipe keywords. ****/
	if (document.getElementById("haveRecipeKeywords")) {
		initRecipeKeywords();
	}
}

/**
 *
 */
function toggleErrorInfo() {
	el=document.getElementById("error-info");

	if (el.style.display=="none")
		el.style.display="block";

	else
		el.style.display="none";
}

/**
 *
 */
function customCartClicked() {
	var contents=document.getElementById("cartContents");

	var popupEl=document.getElementById("cart_content_popup");
	if (popupEl)
		popupEl.style.display="none";
		

	if (contents.style.display=="none") {
		contents.style.display="block";
	}

	else {
		contents.style.display="none";
	}

	return false;
}

/**
 *
 */
function toggleRecipeType() {
	var el=document.getElementById("recipeType");

	if (el.style.display=="none")
		el.style.display="block";

	else
		el.style.display="none";

	return false;
}

/**
 *
 */
function updateRecipeKeywords() {
	var els=document.getElementsByName("__keywordsCheck");
	var targetEl=document.getElementById("keywordEntry");
	var i;

	targetValue="";

	for (i=0; i<els.length; i++) {
		el=els[i];

		if (el.checked)
			targetValue+=el.value+" ";
	}

	targetEl.value=targetValue;
}

/**
 *
 */
function initRecipeKeywords() {
	var els=document.getElementsByName("__keywordsCheck");
	var targetEl=document.getElementById("keywords");
	var i;

	for (i=0; i<els.length; i++) {
		el=els[i];

		if (targetEl.value.indexOf(el.value)>=0)
			el.checked=true;
	}
}

