//JQuery Version
$(window).bind('unload',function(){
  if(typeof GUnload=='function'){
    GUnload();
  }
});
$(document).ready(function(){
  if(typeof MOGI_sortableList=='function'){
    MOGI_sortableList();
  }

  if(typeof initSlideChannels=='function'){
    initSlideChannels();
  }
  if(typeof DsGoogleMap=='function'){
    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);
          })
        }
      });
    }
  }
  if(typeof dojo=='object'){
    dojo.addOnLoad( function (){
      setRecipeDefaultValues();
    });
  }

  if($('#imagebox').length>0){
    $('#imagebox').nivoSlider({
      controlNav: false,
      pauseTime: 4000,
      prevText: 'Zurück', // Prev directionNav text
      nextText: 'Weiter',
      controlNavThumbs:true,
      controlNavThumbsFromRel:true
    });

  }
  _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($('#adserver_linktippswebconomy') && $('#adserver_linktippsgoogle')){
    if($('#adserver_linktippswebconomy')){
      AdSlides.push($('#adserver_linktippswebconomy'));
    }
    if($('#adserver_linktippsgoogle')){
      AdSlides.push($('#adserver_linktippsgoogle'));
    }
    $('#slidingads').bind('mouseout',
      function(){ 
        AdSliding=1;
      }
      );
    $('#slidingads').bind('mouseover',
      function(){ 
        AdSliding=0;
      }
      );
    if($('#adserver_linktippswebconomy_tab').length>0){
      $('#adserver_linktippswebconomy_tab').bind('mouseout',
        function(){ 
          AdSliding=1;
        }
        );
    }
    if($('#adserver_linktippsgoogle_tab').length>0){
      $('#adserver_linktippsgoogle_tab').bind('mouseout',
        function(){ 
          AdSliding=1;
        }
        );
    }
    if($('#adserver_linktippswebconomy_tab').length>0){
      $('#adserver_linktippswebconomy_tab').bind('mouseover',
        function(){ 
          i=1;
          AdSliding=1;
          SlideAdvert(0);
          AdSliding=0;
        }
        );
    }
    if($('#adserver_linktippsgoogle_tab').length>0){
      $('#adserver_linktippsgoogle_tab').bind('mouseover',
        function(){ 
          i=0;
          AdSliding=1;
          SlideAdvert(0);
          AdSliding=0;
        }
        );
    }
  }
  if($('#addusercomment').length>0){
    $('#addusercomment').bind('click',
      function(){ 
        $('#commentformular').show();
      }
      );
  }
  setInterval("SlideAdvert(1000)",15000);
  var cookie = readCookie("style");
  var title = cookie ? cookie : getPreferredStyleSheet();
  
  setActiveStyleSheet(title);
});

var AdSlides = [];
var i=0;
var AdSliding=1;
function SlideAdvert(Duration) {
  if(AdSliding==1){
    if(i==AdSlides.length){
      i=0;
    }
    var innerI=i+1;
    if(innerI==AdSlides.length){
      innerI=0;
    }
    $(AdSlides[i]).animate({
      opacity:0.0
    },Duration);
    $(AdSlides[i]).hide();
    $(AdSlides[innerI]).show();
    $(AdSlides[innerI]).animate({
      opacity:1.0
    },Duration);
		
    /*Effect.Fade(AdSlides[i], { duration:Duration, from:1.0, to:0.0,queue:'front'});
		Effect.Appear(AdSlides[innerI], { duration:Duration, from:0.0, to:1.0 ,queue:'end'});*/
    i=i+1;
  }
}
function str_replace(search, replace, subject) {
  return subject.split(search).join(replace);
}
function setRecipeDefaultValues(){ //reinitialize recipe ingredients
  $('.selectvalues').each(function(){
    dijit.byId(str_replace('_default','',$(this).attr('id'))).setAttribute('value',$(this).val());
  }
  )
}


function setActiveStyleSheet(title) {
  var i, a, main;
  var newStylesheetIsSet=false;
  var preferedStylesheet=getPreferredStyleSheet();
  $("link").each(function(){
    if($(this).attr("rel").indexOf("style") != -1 && $(this).attr("title")) {
      $(this).attr('disabled',true);
      if($(this).attr("title") == title){
        $(this).attr('disabled',false);
        createCookie("style", title, 365);
        newStylesheetIsSet=true;
      }
    }
  });
  if(newStylesheetIsSet==false && preferedStylesheet!=null){
    setActiveStyleSheet(preferedStylesheet);	  
  }
}

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

function getPreferredStyleSheet() {
  var returnValue=null;
  $("link").each(function(){
    if($(this).attr("rel").indexOf("style") != -1
      && $(this).attr("rel").indexOf("alt") == -1
      && $(this).attr("title")
        ) 
      returnValue=$(this).attr("title");
  });
    
  return returnValue;
}

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 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 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');
  $(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('/');
    requestUrl='/json/guestbook/setguestbook/id/'+urlarray[4]+'/type/'+urlarray[1];
    $.post(
      window.location.protocol+'//'+window.location.hostname+requestUrl,
      {
        'rating-stars':$('#rating-stars').val(),
        'content':$('#rating-content').val(),
        'head':$('#rating-head').val()				
      },
      function(responseArray){
        var li = $('<li/>');
					
        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('');
        setRating(0,'#guestbookrating','#rating-stars');
      }
      );
  }
  return false;
}



function deleteWorkElement(objectID){
  var requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+'xml/delete/type/worker/id/'+objectID;
  $.post(
    requestUrl,
    {},
    function redirect(){
      $('#workElement_'+objectID).remove();
    }
    );
  return true;
}
function addWorkElementeToMain(objectID){
  var url=window.location.pathname;
  var requestUrl;
  if(url=='/'){
    requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+'xml/createlink/id/'+objectID+'/categoryid/1';
  }
  else{
    var urlarray=url.split('/');
    requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+'xml/createlink/id/'+objectID+'/categoryid/'+urlarray[4];
  }
  $.post(
    requestUrl,
    {
    },
    function redirect(){
      document.location.reload();
    }
    );
  return true;
}
function moveWorkElementeToMain(objectID){
  var url=window.location.pathname;
  var requestUrl;
  if(url=='/'){
    requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+'xml/moveelement/id/'+objectID+'/categoryid/1';
  }
  else{
    var urlarray=url.split('/');
    requestUrl=window.location.protocol+'//'+window.location.hostname+'/'+'xml/moveelement/id/'+objectID+'/categoryid/'+urlarray[4];
  }
  $.post(
    requestUrl,
    {},
    function redirect(){
      document.location.reload();
    }
    );
  return true;
}
//TODO: rewrite to jquery
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;
}
