var queryText=false;
var map=false;
$(document).ready(function(){
	if($.browser.msie==true && $.browser.version=='7.0' ){
		if(location.pathname=='/'){
			$('#container_service').css('margin-left',-200);
		}
		else{
			$('#container_service').css('margin-left',80);
			
		}
	}
	if(typeof MOGI_sortableList=='function'){
		MOGI_sortableList();
	}
	if(typeof MOGI_dragableServiceBox=='function'){
		MOGI_dragableServiceBox();
	}
	if(typeof MOGI_googlemap=='function'){
		MOGI_googlemap();
	}
	if(typeof MOGI_workbox=='function'){
		MOGI_workbox();
	}
	if(typeof MOGI_wastebin=='function'){
		MOGI_wastebin();
	}
	
	if(typeof dojo=='object'){
		dojo.addOnLoad( function (){setRecipeDefaultValues();});
	}
	if(typeof DsGoogleMap=='function' && $('#address-Gmap').length>0){
		var url=location.pathname;
    var url_array=url.split('/');
    var objectType = url_array[1];
    var linkid = url_array[4];
    
    map = new DsGoogleMap('address');
    map._objectType = objectType;
    map._objectId = linkid;
        
    map.initialize();
    
    //if(typeof clientLocation != 'undefined') {
    $('#clientLocation').click(function(){
        //if($('#clientLocation').is(':checked')) {
            map.clearMarkers();
            map.focusClientLocation();
        //}
    });
    if(typeof searchQuery != 'undefined' && typeof searchQuery !='undefined' &&  searchQuery != '') {
      $('#search_form').submit(function() {
        map.clearMarkers();
        map.setFilter('10', $('#searchtextfieldID').val());
        return false;
      });
      map.setFilter('10', searchQuery);
    }
    else {
      if($('#'+map.getMapIdentifier()).attr('latitude') == undefined || $('#'+map.getMapIdentifier()).attr('longitude') == undefined){
        map.setObjectPositionByAddress(objectType, linkid);
      }
      map.loadRootObject(objectType, linkid, function() {
        map.focusRootObject();
        if($('#'+map.getMapIdentifier()).attr('dragable')=='dragable') {
          map.getRootMarker().setDraggable(true);
          $('.setPos4Addr').click(function() {
            map.setObjectPositionByAddress(objectType, linkid);
          })
        }
      });
    }
	}
	_uacct = false;
	if(window.location.hostname=='www.dinnersearch.at'){
		_uacct='UA-241256-1';
	}
	if(window.location.hostname=='suche.dinnersearch.at'){
		_uacct='UA-66992-4';
	}
	if(window.location.hostname=='www.dinnersearch.de'){
		_uacct='UA-66992-6';
	}
	if(window.location.hostname=='mein-restaurant.at'){
		_uacct='UA-66992-1';
	}
	if(window.location.hostname=='www.mein-restaurant.at'){
		_uacct='UA-241256-3';
	}
	if(window.location.hostname=='www.dinnersearch.com'){
		_uacct='UA-241256-2';
	}
	if(_uacct!=false){ //new google api 2009
		try {
			var pageTracker = _gat._getTracker(_uacct);
			pageTracker._trackPageview();
		} catch(err) {}
	}
	if($('#searchquerytext').length!=0){
		$('#searchquerytext').val('Suchbegriffe: Name, Plz, Typ, ...');
		 $("#searchquerytext").focus(function () {
			 if(queryText==false){
				 $(this).val('');
				 $(this).css("color",'rgb(0,0,0)');
				 queryText=true;
			 }
	    });
		 
		 $("#searchcloudform").submit(function () {
			 if(queryText==false){
				 $("#searchquerytext").val('');
				 $(this).css("color",'rgb(0,0,0)');
				 queryText=true;
			 }
	    });
	}
	if($('#contentboxes').length!=0){
		//set click-event to link of header
		$('.contentbox_header').each(function(){
			$(this).parent().click(function(){
				location.href=$(this).find('a').attr('href');
				
			});
		});
	}

	if($('#restaurantdetaillist').length!=0){
		$('#restaurantdetaillist li div.restaurantdetail').each(function(){
			$(this).bind('click',function(){
				location.href=$(this).find('h2 a').attr('href');
			});
		});
	}
	//var cookie = readCookie("style");
	//var title = cookie ? cookie : getPreferredStyleSheet();
	if($('#slider').length>0){
		$('#slider').nivoSlider({
			controlNav: false,
			pauseTime: 4000,
			prevText: 'Zurück', // Prev directionNav text
			nextText: 'Weiter'

		});
	}
	//if($('#startrestaurantdetaillist').length>0){
	//	slideShow();
	//}
	//setActiveStyleSheet(title);
});
function getLongLat() {    
//		var geocoder = new google.maps.Geocoder(); // used for geocoding
//		var address = document.getElementById("address-postal").value;    
//		if (geocoder) {      
//				geocoder.geocode( { 'address': address}, function(results, status) {        
//						if (status == google.maps.GeocoderStatus.OK) {          
//								map.setCenter(results[0].geometry.location);          
////								var marker = new google.maps.Marker({
////										map: map,
////										position: results[0].geometry.location
////								});
//						} 
//						else {
//								alert("Geocode was not successful for the following reason: " + status);
//						}
//				});
//		}
}
function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function setActiveStyleSheet(title) {
  linkElements=$('link');
  linkElements.each(function(){
	 if($(this).attr('rel').indexOf('stylesheet')!=-1 && $(this).attr('title').length!=0){
		 if($(this).attr('title')==title){
			 $(this).attr('disabled',false);
			 createCookie('style',title,365);
		 }
		 else{
			 $(this).attr('disabled',true);
		 }
	 }
	 
  });
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
function setRating(number,ulidentifier,inputIdentifier){
	$(ulidentifier).removeClass('stars_1');
	$(ulidentifier).removeClass('stars_2');
	$(ulidentifier).removeClass('stars_3');
	$(ulidentifier).removeClass('stars_4');
	$(ulidentifier).removeClass('stars_5');
	$(ulidentifier).removeClass('stars_6');
	if(number==-1){
			$(ulidentifier).addClass('stars_0');
	}
	else{
		$(ulidentifier).addClass('stars_'+number);
	}
	$(inputIdentifier).val(number);
	return false;
}
function saveRating(){
	if($('#rating-content').val()==""){
		alert('Geben Sie bitte einen Kommentar ein, weshalb Sie diese Berwertung abgeben!')
	}
	else{
		var url=location.pathname;
		var urlarray=url.split('/');
		var infos={};
//		'service','food','drinks','rooms','hygiene','stars'
		if($('#rating-stars').length>0 && $('#rating-stars').val()!=-1){
				infos['rating-stars']=$('#rating-stars').val();
		}
		if($('#rating-service').length>0 && $('#rating-service').val()!=-1){
				infos['rating-service']=$('#rating-service').val();
		}
		if($('#rating-food').length>0 && $('#rating-food').val()!=-1){
				infos['rating-food']=$('#rating-food').val();
		}
		if($('#rating-drinks').length>0 && $('#rating-drinks').val()!=-1){
				infos['rating-drinks']=$('#rating-drinks').val();
		}
		if($('#rating-rooms').length>0 && $('#rating-rooms').val()!=-1){
				infos['rating-rooms']=$('#rating-rooms').val();
		}
		if($('#rating-hygiene').length>0 && $('#rating-hygiene').val()!=-1){
				infos['rating-hygiene']=$('#rating-hygiene').val();
		}
		infos['content']=$('#rating-content').val();
		infos['head']=$('#rating-head').val();
		requestUrl='/json/guestbook/setguestbook/id/'+urlarray[4]+'/type/'+urlarray[1];
		$.post(
				window.location.protocol+'//'+window.location.hostname+requestUrl,
				infos,
				function(responseArray){
					var li = $('<li/>');
					//TODO append for multiple ratings
					li.append($('<div/>').addClass('guestbookhead').text(responseArray.head));
					li.append($('<div/>')
								.addClass('guestbookentry_headerline').text(responseArray.created+' - '+responseArray.name)
								.append($('<div/>').addClass('displaystars stars_'+responseArray.rating)));
					li.append($('<div/>').html(responseArray.content));
					li.prependTo($('#guestbooklist'))
					resetBackground('#guestbooklist');
					$('#rating-content').val('');
					$('#rating-head').val('');
					//		'service','food','drinks','rooms','hygiene','stars'
					if($('#rating-stars').length>0){
						setRating(-1,'#guestbookrating_stars','#rating-stars');
					}
					if($('#rating-service').length>0){
						setRating(-1,'#guestbookrating_service','#rating-service');
					}
					if($('#rating-food').length>0){
						setRating(-1,'#guestbookrating_food','#rating-food');
					}
					if($('#rating-drinks').length>0){
						setRating(-1,'#guestbookrating_drinks','#rating-drinks');
					}
					if($('#rating-rooms').length>0){
						setRating(-1,'#guestbookrating_rooms','#rating-rooms');
					}
					if($('#rating-hygiene').length>0){
						setRating(-1,'#guestbookrating_hygiene','#rating-hygiene');
					}
					
				}
		);
	}
	return false;
}
function resetBackground(listidentifier){
	currentClass='bglight';
	$(listidentifier).children().each(function(){ 
		$(this).removeClass('bglight');
		$(this).removeClass('bgdark');
		if(currentClass=='bglight'){
			currentClass='bgdark';
		}
		else{
			currentClass='bglight';
		}
		$(this).addClass(currentClass);
		});
}
function addWorkbox(parameters){
	//addWorkbox('type:article,id:<?php echo $linkItem->id ?>')
	var parameterArray=parameters.split('-');
	var options = new Object();
	for(i=0;i<parameterArray.length;i++){
		info=parameterArray[i].split(':');
		options[info[0]]=info[1];
	}
	var url=window.location.pathname;
	var requestUrlArray=new Array();
	
	requestUrlArray.push('xml');
	requestUrlArray.push('workbox');
	for(key in options){
		requestUrlArray.push(key);
		requestUrlArray.push(options[key]);
	}
	
	requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+requestUrlArray.join('/');
	//  /image/list/type/recipe/id/1357
	// /xml/sortlist/type/image/object/recipe/id/{id}
 $.post(requestUrl,{},
    function(data){
      document.location.reload();
    }
 );
	return true;
}
