var newwindow;
function poptastic(url)
{
	newwindow=window.open(url,'name','height=500,width=500,top=100,left=100resizable=yes,scrollbars=yes,toolbar=no,status=no,resizable=no,scrollbars=no,toolbar=no,status=no,location=no');
	if (window.focus) {newwindow.focus()}
}


function calculatePrice(){
	
	var date_from = document.getElementById("db_from_date").value;
	var date_to = document.getElementById("db_till_date").value;
	var date_from_str = date_from.replace("-", "/").replace("-", "/");
	var date_to_str = date_to.replace("-", "/").replace("-", "/");
	document.getElementById("db_purchase_price").value = days_between(new Date(date_from_str),new Date(date_to_str))*document.getElementById("db_daily_price").value;
}


function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)
}
function SubmitButtonPaging(pId){
	 
    document.forms[0].action.value = "paging";
    document.forms[0].requestedPage.value = pId;
    document.forms[0].submit();
 
}
function show_magnifier(item){
		  var newdiv = document.createElement('div');
		  var divIdName = 'myDiv';
		  newdiv.setAttribute('id',divIdName);
		  newdiv.style.backgroundImage = "url(./images/magnifier.gif)";
		  newdiv.style.zIndex ="1000";
		  newdiv.style.position = "relative";
		  newdiv.style.left = "10px";
		  newdiv.style.top = "10px";
		  newdiv.innerHTML ="kjhkhkjh&nbsp;";
		  item.appendChild(newdiv);
}


function initRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        isIE = true;
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
}
function checkUserDataCallback(responseXML, field) {
	   var msg = responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;
	   if (msg == "false") {
	       var mdiv = document.getElementById(field+"_state");
	       mdiv.className = "invalid";
	       mdiv.innerHTML = "Foglalt";
	    } else {
	       var mdiv = document.getElementById(field+"_state");
	       mdiv.className = "valid";
	       mdiv.innerHTML = "Szabad";
	    }  
	}

function checkUserData(field) { 
	
    var target = document.getElementById(field);
    if (target.value!=""){
    	
    var url = "/dataCheckerServlet?operation="+field+"&"+field+"="+encodeURIComponent(target.value);
    var req = initRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
            	checkUserDataCallback(req.responseXML, field);
            } else if (req.status == 204){
                clearTable();
            }
        }
    };
    req.open("GET", url, true);
    req.send(null);
    }else{
    	var mdiv = document.getElementById(field+"_state");
    	mdiv.className = "bp_valid";
	    mdiv.innerHTML = "";
    }
}


function add_to_favorites(product_id, shop_id) {
   
        var url = "/addToFavoritesServlet?action=add&product_id="+product_id;
        var req = initRequest();
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                if (req.status == 200) {
                    parseMessages(req.responseXML);
                } else if (req.status == 204){
                    clearTable();
                }
            }
        };
        req.open("GET", url, true);
        req.send(null);
        element = document.getElementById("favorites_div"+product_id);
        element.innerHTML = "  <img src=\"./images/ekszerkereso/star.gif\" />";
    
}

function promote_site(promoter_name, promoter_email, recipient_email) {
	   
	promoter_name=document.getElementById("promoter_name").value
	promoter_email=document.getElementById("promoter_email").value
	recipient_email=document.getElementById("recipient_name").value
    var url = "/promoteSiteServlet?name="+promoter_name+"&promoter_email="+promoter_email+"&recipient_email="+recipient_email;
    var req = initRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                parseMessages(req.responseXML);
            } else if (req.status == 204){
                clearTable();
            }
        }
    };
    req.open("GET", url, true);
    req.send(null);
    element = document.getElementById("promote_site_message");
    element.innerHTML = "<br /><span class=\"label_bold\">Üzenetét elküldtük</span><br /><br />";

}


function update_box_state(box_name) {
	   
    var url = "/boxStateServlet?box_name="+box_name;
    var req = initRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                parseMessages(req.responseXML);
            } else if (req.status == 204){
                clearTable();
            }
        }
    };
    req.open("GET", url, true);
    req.send(null);
}

function remove_from_favorites(product_id, shop_id) {
	   
    var url = "/addToFavoritesServlet?action=remove&product_id="+product_id;
    var req = initRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            if (req.status == 200) {
                parseMessages(req.responseXML);
            } else if (req.status == 204){
                clearTable();
            }
        }
    };
    req.open("GET", url, true);
    req.send(null);
    element = document.getElementById("product"+product_id);
    element.innerHTML = "";
  

}

function returnSelected(selected){

	 window.opener.document.getElementById('db_icon_image').value=selected
	 window.close(); 
	 }

function SubmitButton(pAction){
	     document.forms[0].action.value = pAction;
	     document.forms[0].submit();
	}

function SubmitButtonTwoParams(pAction, pId){
	 
   document.forms[0].action.value = pAction;
   document.forms[0].currentId.value = pId;
   document.forms[0].submit();

}
function SubmitButton_2(pAction){
	
	if (document.getElementById("keyword").value!=""){
	window.location= "/advancedSearchAction.do?keyword="+document.getElementById("keyword").value;
	}
	
}

function ShopSelector(shopId){
	if ("-13"!=shopId){
	window.location= "/productListLoadAction.do?shop_id="+shopId;
	}
}

var browserType;
var show = true;
var div_names = new Array();
if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {
browserType= "gecko"
}
function handle_page_change(url, selectObject, lastParam){
	window.location=url+selectObject.value+lastParam;
}

function handle_page_change2(url, pagenumber, lastParam){
	if (pagenumber==null || pagenumber==""){
		window.location=url+"1"+lastParam;
	}else{
		window.location=url+pagenumber+lastParam;
	}
}

function getdivState(divName){
	for (i=0; i<div_names.length; i++)
	{
	if (div_names[i][0]==divName){
		var div_state=div_names[i][1];
		if (div_names[i][1]==true){
			div_names[i][1]=false;
			}else{
				div_names[i][1]=true;
				}
		return div_state;
		}
	}
	var new_div= new Array();
	new_div[0]=divName;
	new_div[1]=false;
	div_names.push(new_div);
	return true;
}

function hideShow(divName){
	update_box_state(divName);
	show =getdivState(divName);
	
	if (show){
			hide2(divName);
			show=false;
		}else{
			show2(divName);
			show=true;
		}
}

function showHide(divName){
	show =getdivState(divName);
	
	if (show){
		show2(divName);
		show=true;
	}else{
		hide2(divName);
		show=false;
	}
}

function showHideAddress(divName, checkbox){
	if (checkbox.value!='y'){
		hide2(divName);
	}else{
		show2(divName);
	}
}

function hide2(divName) {
 if (browserType == "gecko" )
    document.poppedLayer =
        eval('document.getElementById("'+divName+'")');
 else if (browserType == "ie")
    document.poppedLayer =
       eval('document.getElementById("'+divName+'")');
 else
    document.poppedLayer =
       eval('document.layers["'+divName+'"]');
 document.poppedLayer.style.display = "none";
}

function show2(divName) {
 if (browserType == "gecko" )
    document.poppedLayer =
        eval('document.getElementById("'+divName+'")');
 else if (browserType == "ie")
    document.poppedLayer =
       eval('document.getElementById("'+divName+'")');
 else
    document.poppedLayer =
        eval('document.layers["'+divName+'"]');
 document.poppedLayer.style.display = "inline";
}

function IsNumeric(sText)

{
	if (sText==""){
		return false;
	}
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

function setShopList(shop_id, shopName, shopAddress, longitude, latitude) {
	var shopData = new Array();
	shopData['name'] = shopName;
	shopData['address'] = shopAddress;
	shopData['longitude'] = longitude;
	shopData['latitude'] = latitude;
	shopData['shop_id'] = shop_id;
	return shopData;
}


function initialize(pagename, canvasname) {
	  gmapsPagename = pagename;
	  gmapsCanvasname = canvasname;
	  if (gmapsPagename == "map") initgmaps(gmapsPagename, gmapsCanvasname);
	}
var hya_point;

function initgmaps(pagename, canvasname) {
	  var init_lat = 47.49902477948121;
	  var init_lng = 19.044156074523926;
	  var init_point;
	  init_point = new GLatLng(init_lat,init_lng);
	  if (GBrowserIsCompatible()) {
	    map = new GMap2(document.getElementById(canvasname));
	    map.setCenter(new GLatLng(init_lat, init_lng), 15);
	    geocoder = new GClientGeocoder();
	    map.addControl(new GSmallMapControl());

	   
	    var hereyouareIcon = new GIcon(G_DEFAULT_ICON);
			//hereyouareIcon.image = "images/ekszerkereso.hu/web/images/holgyekorome/box1_left_bottom_bg.gif";
			//hereyouareIcon.iconSize = new GSize(32, 32);
			hereyouareIcon.iconAnchor = new GPoint(15,31);
			hereyouareIcon.shadow = "";
	 		hereyouareMarkerOptions = { icon:hereyouareIcon };
	 		
	 		if (pagename == "map") {
	      GEvent.addListener(map,"click", function(overlay,point) {
	        if (overlay == null) {
	          hya_point = point;
	          setCoords();
	          if (point=null){
	        	  point=init_point;
	          }
	          showShops(shopList, getVal("distance"), hya_point);
	        }
	      });
	    }
	    gmapsLoaded = true;
	    drawCircle(init_lng,init_lat,500);
	  }
	}

function addShopMarker(shop_id, name, address, longitude, latitude) {
	
	var geocoder = new GClientGeocoder();

	  var colorMarker = new GIcon(G_DEFAULT_ICON);
	 // if (i == undefined)
	  	//colorMarker.image = "markers/b.gif";
	//	else
	  	//colorMarker.image = "images/ekszerkereso.hu/web/images/holgyekorome/box1_left_bottom_bg.gif";
		colorMarker.iconSize = new GSize(16, 32);
		colorMarker.iconAnchor = new GPoint(7,32);
		colorMarker.shadow = "";
		var colorMarkerOptions = { icon:colorMarker, 
			tooltip: name };

	  var point;
	  if (longitude!="null" && latitude!="null"){
		  point = new GLatLng(longitude,latitude);
		  var marker = new GMarker(point, colorMarkerOptions);
		  GEvent.addListener(marker,"click", function() {
		      toggle_info_box(name, "");
		    });
		  

		  GEvent.addListener(marker,"mouseover", function() {
		    marker.openInfoWindow("<span class=\"google_label\"><b>"+name+"</b><br>"+address+"</span>");
		  });

		  GEvent.addListener(marker,"mouseout", function() {
		    marker.closeInfoWindow();
		  });
		  map.addOverlay(marker);
	  }else
	  {
		  point = geocoder.getLatLng(address, function aaa(point){
			  if (!point){
				  
			  }else{
				  var marker = new GMarker(point);
				  save_gps_coordinates(shop_id, point.lat(), point.lng());
				  }
			  GEvent.addListener(marker,"click", function() {
			      toggle_info_box(name, "");
			    });
			  

			  GEvent.addListener(marker,"mouseover", function() {
				  marker.openInfoWindow("<span class=\"google_label\"><b>"+name+"</b><br>"+address+"</span>");
			  });

			  GEvent.addListener(marker,"mouseout", function() {
			    marker.closeInfoWindow();
			  });
	  map.addOverlay(marker);
});
		  
	

	   
	   
	  
	 
	}
	  }

function showShops(shopList, distance, point){
	var geocoder = new GClientGeocoder();
	  for (i=0; i < shopList.length; i++) {
		 var shopInfo=shopList[i];
		 var shop;
		
		 if (point==null){
			 point=map.getCenter();
		 }
		 
		if (shopInfo['longitude']=="null" && shopInfo['latitude']=="null"){ 
			shop = geocoder.getLatLng(shopInfo['address'],function aaa(point){
				save_gps_coordinates(shopInfo['shop_id'], point.lat(), point.lng());
			});
			
		}
		 shop = new GLatLng(shopInfo['longitude'],shopInfo['latitude']);		  
		 shop_dist=shop.distanceFrom(point)
		 if (shop_dist<=distance){
			 addShopMarker(shopInfo['shop_id'],shopInfo['name'],shopInfo['address'],shopInfo['longitude'],shopInfo['latitude']);
		 }
		  
	  }
}

function drawCircle(bx,by,r) {
	  hya_point = new GLatLng(by,bx);
	  hya = new GMarker(hya_point,hereyouareMarkerOptions);
	  map.addOverlay(hya);
	  if (r <= 6000) {
		r=r*0.95;
	    coordinates = new Array();
	    xd = 1000*111.322;
	    yd = 1000*Math.cos(by*3.141592/180)*111.322;
	    for (i=0; i <= 24; i++) {
	      pntr = (i*15)*3.141592/180;
	      coordinates[i] = new GLatLng(by+r/xd*Math.cos(pntr),bx+r/yd*Math.sin(pntr));
	    }
	    polygonOverlay = new GPolyline(coordinates, "#0000ff", 4);
	    map.addOverlay(polygonOverlay);
	  }
	}

function setCoords() {
	  if ( hya_point ) {
		  var dist =  getVal("distance");
		  showShops(shopList, dist, hya_point);
		  
	       if (dist == 500) { map.setZoom(15);
	      } 
	       else if (dist > 500) { map.setZoom(13);
	      }
	      map.panTo(hya_point);
	      map.clearOverlays();
	      drawCircle(parseFloat(hya_point.x),parseFloat(hya_point.y),parseFloat(dist));
	  } else {
	    return false;
	  }
	}

function getVal(elementName) {
	  var obj = document.getElementsByName(elementName);

	  if ( (obj[0].type == "radio") ) {
	    for (var i = 0; i < obj.length; i++) {
	      if (obj[i].checked)
	        return obj[i].value;
	    }
	  } else if ( (obj[0].type == "checkbox") ) {
	    for (var i = 0; i < obj.length; i++) {
	      if (obj[i].checked)
	        return obj[i].checked;
	    }
	  }

	  return obj[0].value;
	}


function clearValue(inputToClear){
	inputToClear.value="";
}
