dojo.require("dojo.io.*");
dojo.require("dojo.lfx.extras");
dojo.require("dojo.widget.Dialog");
//dojo.require("dojo.lfx.*");
//dojo.require("dojo.event.*");
//dojo.require("dojo.widget.Toaster");
//dojo.require("dojo.lang.common");
//dojo.require("dojo.undo.browser");

var images = new Array();
var wipe=false;
var style=false;
var toast=null;
//var djConfig={
//      isDebug: true,
//      preventBackButtonFix: false
//    };
var siteState;
var firstHash=location.hash;

dojo.addOnLoad(init);

function init(){

  //History und back forward Funktion
  siteState={
  	back: function() {},
  	forward: function() {}
  };
  dojo.undo.browser.setInitialState(siteState);

  new preloadImages(new Array("bilder/main_low.png","bilder/rahmen_links.jpg","bilder/rahmen_rechts.jpg","bilder/rahmen_oben.jpg","bilder/rahmen_unten.jpg","bilder/rahmen_oben_links.jpg","bilder/rahmen_unten_links.jpg","bilder/rahmen_oben_rechts.jpg","bilder/rahmen_unten_rechts.jpg","bilder/loading12x12.gif"),'callBackPreload');
}

//Site loading funktionen---------------------------------------------
function loadSite(id){
  getData('mainContainer',{'inhalt':id},false,'leer');
}

function getData(id,vars,callBack,statusText){
  if(!wipe || statusText=="Willkommen"){
    wipe=true;
    var statusNode=dojo.byId("titleContainer");
    if (statusNode) dojo.lfx.html.fadeOut("titleContainer", 400, null, function(){
      document.getElementById("titleContainer").innerHTML='<img src="bilder/loading12x12.gif" border="0"> Seite wird geladen...';
      dojo.lfx.html.fadeIn("titleContainer", 400).play();
    }).play();
  	dojo.io.bind({
  		url: "inhalt.php5",
  		changeUrl: vars.inhalt,
  		back: function() { back(); },
  		//forward: function() { forward(); },
  		method: 'post',
  		content: vars,
      useCache: true,
  		load: function(type, data, evt){
  			dojo.lfx.html.fadeWipeOut(id, 400, null, function(){
          if (data.search(/^{.*}/m)!=-1){
            eval("data="+data);
            document.getElementById(id).innerHTML=data.inhalt;
            statusText=data.navigation;
            document.title="SRB Landtechnik - "+data.documentTitle;
          }else{
            document.getElementById(id).innerHTML=data
            document.title="SRB Westprignitzer Landtechnik GmbH";
          }
  				hideAndLoadPics();
  				if (statusNode) dojo.lfx.html.fadeOut("titleContainer", 400, null, function(){
            document.getElementById("titleContainer").innerHTML=statusText;
            dojo.lfx.html.fadeIn("titleContainer", 400).play();
          }).play();
  				dojo.lfx.html.fadeWipeIn(id, 1200, null, function(){wipe=false;}).play();
  				if(callBack){
  		      var evalString=callBack+"()";
            eval(evalString);
  				}
  			}).play();
  		},
  		error: function(type, error){ alert("Fehler! Überprüfen sie die Aktualität Ihres Browsers. Wir empfehlen Mozilla Firefox."); },
  		mimetype: "text/plain"
  	});
	}
}

function hideAndLoadPics(){
	for(i=0;document.getElementsByTagName('img')[i];i++){
    images[i]=document.getElementsByTagName('img')[i];
		if(!images[i].complete){
		  dojo.lfx.html.fadeOut(images[i],1).play();
		  images[i].onload=function(){
        dojo.lfx.html.fadeIn(this,400).play();
      }
		}
	}
}

function back(){
  var hash=location.hash;
  if(hash){
    loadSite(hash.substring(1,hash.length));
  }
}

function forward(){
  var hash=location.hash;
  if(hash){
    loadSite(hash.substring(1,hash.length));
  }
}

//---------------------------------------------------------
//callBack Funktionen -------------------------------------
function callBackInit(){
  menue = new Menue();
  //var vars = {id:"toast",positionDirection:"br-left",showDelay:"3000",messageTopic:"Angebot"};
  //toast = dojo.widget.createWidget("toaster",vars);
  //toast = dojo.widget.byId("toast");

  if(firstHash && firstHash!="#init"){
    getData("mainContainer",{"inhalt":firstHash.substring(1,firstHash.length)},false,"Willkommen");
  }else{
    getData("mainContainer",{"inhalt":2},false,"Willkommen");
  }
}

function callBackKarte(){
  mapLoad();
}
//---------------------------------------------------------
//Menü Funktionen------------------------------------------
function MenuePoint(node){
  this.node=node;
  this.wipedOut=true;
  dojo.lfx.wipeOut(node, 1, null, function(node){
    node.style.display="none";
  }).play();
}

function Menue(){
  var menuewipe=false;
  var elements=document.getElementById("menueContainer").childNodes;
  var menuePoints = new Array();
  var ii=0;
  for(var i=0; i<elements.length; i++) {
    if(elements[i].id){
      if(elements[i].id.slice(0,5)=="menue"){
        menuePoints[ii] = new MenuePoint(elements[i]);
        ii++;
      }
    }
  }
  this.wipe=function(id){
    if(!menuewipe){
      menuewipe=true;
      var wipingNode=document.getElementById(id);
      for(var i=0; i<menuePoints.length; i++){
        if(menuePoints[i].node==wipingNode){
          var node=menuePoints[i].node;
          if(menuePoints[i].wipedOut){
            menuePoints[i].wipedOut=false;
            dojo.lfx.wipeIn(menuePoints[i].node, 600, null, function(){menuewipe=false;}).play();
          }
          else{
            //dojo.lfx.wipeOut(menuePoints[i].node, 600, null, function(node){
            //  node.style.display="none";
              menuewipe=false;
            //}).play();
            //menuePoints[i].wipedOut=true;
          }
        }else{
          if(!menuePoints[i].wipedOut){
            dojo.lfx.wipeOut(menuePoints[i].node, 600, null, function(node){
              node.style.display="none";
            }).play();
            menuePoints[i].wipedOut=true;
          }
        }
      }
    }
  }
}
//---------------------------------------------------------
//Bilder Preloader-----------------------------------------
function preloadImages(images,callBack){
  //alert("BOING 1");
  var imagesCount=images.length;
  var counter=0;
  var imagesContainer=new Array();
  
  this.imageLoaded=function(){
    //alert("BOING 3");
    counter++;
    //alert(counter+" "+imagesCount);
    if(counter==imagesCount){
      callBackPreloadImages();
    }
  }
  
  for (var i=0;i<images.length;i++)
  {
    //alert("BOING 2");
      imagesContainer[i]=new Image();
      imagesContainer[i].src=images[i];
    if(!imagesContainer[i].complete){
      imagesContainer[i].onload=this.imageLoaded;
    }
    else{
      this.imageLoaded();
    }
  }
}

function callBackPreloadImages(){
  getData("initContainer",{"inhalt":"init"},"callBackInit");
}
//--------------------------------------------------------

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

function switchStyle(){
//  showToaster();
  if(style){
    style=false;
    setActiveStyleSheet('normale Schriftgröße');
  }
  else{
    style=true;
    setActiveStyleSheet('größe Schrift');
  }
}

//andere Funktionen
function showToaster(){
  dojo.event.topic.publish("Angebot", "größere Schrift: an");
}

function openWindow(site,name,width,height){
  Leftpositionition=(screen.width)?(screen.width-w)/2:100;
  Toppositionition=(screen.height)?(screen.height-h)/2:100;
  settings='width='+width+',height='+height+',top='+Toppositionition+',left='+Leftpositionition+',scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no';
  window.open(site,name,settings);
}

function openPicture(url){
  //document.getElementById("dialog").setContent('<a href="javascript:;"><img border="0" alt="anklicken um zu schließen" title="anklicken um zu schließen" onclick="dojo.widget.byId(\'dialog\').hide()" src="'+url+'"></a>');
  dojo.widget.byId("dialog").setContent('<a href="javascript:;"><img border="0" alt="anklicken um zu schließen" title="anklicken um zu schließen" onclick="dojo.widget.byId(\'dialog\').hide()" src="'+url+'"></a>');
	dojo.widget.byId("dialog").show();
}

function search(){
  var jsonData={};
  jsonData.searchtext=document.getElementById("form_search_searchtext").value;
  jsonData.inhalt="search";
  jsonData.error="";
  if(!jsonData.searchtext){
    jsonData.error+="Bitte geben Sie einen Suchtext ein";
  }
  if(jsonData.error!=""){
    dojo.event.topic.publish("Message",{message: jsonData.error, type: "ERROR", delay: 12000});
  }else{
    getData("mainContainer",jsonData,false,false);
  }
}

function sendEMail(){
  jsonData=getContactFormData();
  jsonData.inhalt="sendEMail";
  jsonData.error="";
  if(!jsonData.forename || !jsonData.name){
    jsonData.error+="Bitte geben Sie Vor- und Nachname ein.<hr>";
  }
  if(!jsonData.fon && !jsonData.email){
    jsonData.error+="Bitte geben Sie Ihre Telefon Nummer oder Ihre E-Mail Adresse ein.<hr>";
  }
  if(jsonData.email){
    if(!isValidEMailAdress(jsonData.email)){
      jsonData.error+="Die eingegebene E-Mail Adresse ist nicht korrekt.<hr>";
    }
  }
  if(!jsonData.message){
    jsonData.error+="Bitte geben Sie Ihre Mitteilung ein.<hr>";
  }
  if(jsonData.error!=""){
    dojo.event.topic.publish("Message",{message: jsonData.error, type: "ERROR", delay: 12000});
  }else{
    getData("mainContainer",jsonData,false,false);
  }
}



function getContactFormData(){
  var jsonData={};
  jsonData.company=document.getElementById("form_contanct_company").value;
  jsonData.forename=document.getElementById("form_contanct_forename").value;
  jsonData.name=document.getElementById("form_contanct_name").value;
  jsonData.street=document.getElementById("form_contanct_street").value;
  jsonData.streetNumber=document.getElementById("form_contanct_streetNumber").value;
  jsonData.postcode=document.getElementById("form_contanct_postcode").value;
  jsonData.city=document.getElementById("form_contanct_city").value;
  jsonData.land=document.getElementById("form_contanct_land").value;
  jsonData.email=document.getElementById("form_contanct_email").value;
  jsonData.fon=document.getElementById("form_contanct_fon").value;
  jsonData.fax=document.getElementById("form_contanct_fax").value;
  jsonData.message=document.getElementById("form_contanct_message").value;
  jsonData.titleWoman=document.getElementById("form_contanct_titleWoman").checked;
  jsonData.titleMan=document.getElementById("form_contanct_titleMan").checked;
  return jsonData;
}

function isValidEMailAdress(s){
  var a = false;
  var res = false;
  if(typeof(RegExp) == 'function'){
    var b = new RegExp('abc');
    if(b.test('abc') == true){a = true;}
  }
  if(a == true){
    reg = new RegExp('^([a-zA-Z0-9\\-\\.\\_]+)'+
                     '(\\@)([a-zA-Z0-9\\-\\.]+)'+
                     '(\\.)([a-zA-Z]{2,4})$');
    res = (reg.test(s));
  }else{
    res = (s.search('@') >= 1 &&
           s.lastIndexOf('.') > s.search('@') &&
           s.lastIndexOf('.') >= s.length-5)
  }
  return(res);
}


function print_r(theObj){
  var text="";
  if(theObj.constructor==Array || theObj.constructor==Object){
    text+="<ul>";
    for(var p in theObj){
      if(theObj[p].constructor==Array || theObj[p].constructor==Object){
        text+="<li>["+p+"] => "+typeof(theObj)+"</li>";
        text+="<ul>";
        text+=print_r(theObj[p]);
        text+="</ul>";
      }else{
        text+="<li>["+p+"] => "+theObj[p]+"</li>";
      }
    }
    text+="</ul>";
	}
	return text;
}

