/* =================================================
 *
 * AJAX Script für Praxis Seever Website
 *
 *         (c) Sebastian Kleinau, März 2009
 *         www.sebastian-kleinau.de
 *
 *                             Privatärztliche Praxis
 *                             DM Ekehard Seever
 *                             www.praxis-seever.de
 *
 * =================================================
 */

var viewportwidth;
var viewportheight;

var containerSizeChanged = false;
var mapLarge;
var mapLargeRoute;
var mapLargeRouteError = false;
var mapLargePrintview = false;
var mapLargeScriptLoaded = false;
var mapSmallScriptLoaded = false;
var mapUmzugScriptLoaded = false;

var minWidth = 478;
var minHeight = 41+90;

var oldWidth = 768;
var oldHeight = 41+90;

var activePage = '';
var activePageIntervalFunction;
var loading = false;
var frame;

window.onload = function() {
    // hide content loaded by php for non-javascript users (-> to have the animation)
    $('content').innerHTML = '';
    // get size of the window for resizing functions
    getViewportSize();

    // activate links on the navigation bar
    $('link_start').addEvent('click', function(event) {
        event.stop();
        loadPage('start');
    });
    $('link_mail').addEvent('click', function(event) {
        event.stop();
        loadPage('mail');
    });
    $('link_therapien').addEvent('click', function(event) {
        event.stop();
        loadPage('therapien');
    });
    $('link_impressum').addEvent('click', function(event) {
        event.stop();
        loadPage('impressum');
    });
    $('link_umzug').addEvent('click', function(event) {
        event.stop();
        loadPage('umzug');
    });

    // check url for direct page access (bookmark, ...)
    if(location.hash.length>1) {
        var page = unescape(location.hash.substring(1));
        loadPage(page);
    } else {
    // load the homepage (animated)
        loadPage('start');
        scaleContainer(768, 435);
    }

    // add Event to change page when browser navigation is used
    window.setTimeout("handleBrowserNavigation()", 200);

   var pf = new PulseFade('umzugButton',{
    min: .25,
    max: 1,
    duration: 500,
    times: 10
  });
   $$('#umzugButton').setStyle('left', -2000);
   var umzugSlideFX = new Fx.Elements($$('#umzugButton'), {duration: '1000', transition: 'bounce'});
   var umzugSlideFXDelayed = function() {
       umzugSlideFX.start({
            '0': {
                'left': [-2000, 0]
            }
        });
    pf.start();
   };
   umzugSlideFXDelayed.delay(1000);
}

function handleBrowserNavigation() {
    // only care if # in url and not already working on a change
    if(location.hash.length>1 && loading==false) {
        var page = unescape(location.hash.substring(1));
        if(page != activePage) {
            loadPage(page);
        }
    }
    window.setTimeout("handleBrowserNavigation()", 200);
}

function loadPage(name) {
    // check the lock - if already loading a page then don't handle that request
    if(loading==true) return false;
    // set a lock so there are no multiple requests from double clicks
    // or browser navigation buttons
    loading = true;

    // parse url to load
    var url = 'start.php';
    document.title = 'Praxis Seever | Facharzt für Allgemeinmedizin, Chirurgie, Chirotherapie, Akupunktur, Neuraltherapie';
    if(name=='map') {
        url = 'gmaps.php';
        document.title = 'Praxis Seever | Anfahrt';
    }
    if(name=='mail') {
        url = 'mail.php';
        document.title = 'Praxis Seever | E-Mail Kontaktformular';
    }
    if(name=='therapien') {
        url = 'therapien.php';
        document.title = 'Praxis Seever | Therapie Angebot';
    }
    if(name=='impressum') {
        url = 'impressum.php';
        document.title = 'Praxis Seever | Impressum';
    }
    if(name=='umzug') {
        url = 'umzug.php';
        document.title = 'Praxis Seever | Wir ziehen um!';
    }

    // show "loading" indicator
    showIndicator(true);

    // handle size of container (map view or not, enlarged impressum)
    if(name=='map' && containerSizeChanged==false) {
        maximizeContainer();
        containerSizeChanged = true;
    }
    if(name!='map' && name!='impressum' && containerSizeChanged==true) {
        restoreContainer();
        containerSizeChanged = false;
    }
    if(name=='impressum') {
        scaleContainer(768, viewportheight);
        containerSizeChanged = true;
    }

    // fade out current content
    $('content').morph({opacity: [1.0, 0.0], duration: '1000'});

    // load new content (after delay for fade out)
    (function() {(
            new Request.HTML({
                url: url,
                method: 'get',
                update: 'content',
                evalResponse: 'true',
                onComplete: function(){
                    // on complete do site specific tasks
                    if(name=='start') {
                        // activate mail link on homepage
                        $('link_mail2').addEvent('click', function(event) {
                            event.stop();
                            loadPage('mail');
                        });
                        // activate map link on homepage
                        $('link_map2').addEvent('click', function(event) {
                            event.stop();
                            loadPage('map');
                        });
                        // load google maps script dynamically
                        initGoogleMapsScript('small');
                    };
                    if(name=='map') {
                        // load google maps script dynamically
                        initGoogleMapsScript('large');
                    };
                    if(name=='mail') {
                        // activate send button
                        $('mailformer').addEvent('submit', function(e) {
                            e.stop();
                            sendMail();
                        });
                    }
                    if(name=='impressum') {

                    }
                    if( name == 'umzug' ) {
                        // load google maps script dynamically
                        initGoogleMapsScript('umzug');
                    }
                    // ... fade content back in ...
                    $('content').morph({opacity: [0.0, 1.0], duration: '1000'});
                    // ... convert tooltip class elements to mootools tooltip ...
                    new Tips($$('.tooltip'), { "timeOut": 700});
                    // ... set anchor for bookmarking & browser navigation ...
                    location.hash = "#" + escape(name);
                    if (window.ActiveXObject) {
                        //window.frames["iebm"].window.location.search = "?" + escape(name);
                    }
                    activePage = name;
                    // ... stop showing the "loading" indicator ...
                    showIndicator(false);
                    // ... release the lock to re-allow page loading
                    loading = false;
                }
            }).send()
    )}).delay(1000);
}

function initGoogleMapsScript(site) {
    // abort if script already inserted into header
    if( site=='small' && mapSmallScriptLoaded==true ) {
        mapSmall_Loaded();
        return false;
    }
    if( site=='large' && mapLargeScriptLoaded==true ) {
        mapLarge_Loaded();
        return false;
    }
    if( site=='umzug' && mapUmzugScriptLoaded==true ) {
        mapUmzug_Loaded();
        return false;
    }
    // dynamically load script into header
    //var key = 'ABQIAAAA-twd_Q3vqxeCFBgcUlj9JhSAKeyCh5wU3R1wMOACY17pPEnB6RQV1dFaBC_g8nbLPBWpJn4yyRevqA';
    var key = 'ABQIAAAA-twd_Q3vqxeCFBgcUlj9JhQF-g8JvPWN-bqhWgqPRVCXOtXU_BSSAjlXS-tcurlzc_hrPW9ErObwcg';
    var script = document.createElement("script");
    if(site=='small' ) {
        script.src = "http://www.google.com/jsapi?callback=loadMaps_small&key="+key;
        mapSmallScriptLoaded = true;
    } else if( site == 'umzug' ) {
        script.src = "http://www.google.com/jsapi?callback=loadMaps_umzug&key="+key;
        mapUmzugScriptLoaded = true;
    } else {
        script.src = "http://www.google.com/jsapi?callback=loadMaps_large&key="+key;
        mapLargeScriptLoaded = true;
    }
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadMaps_small() {
    google.load("maps", "2", {"callback": mapSmall_Loaded});
}

function loadMaps_umzug() {
    google.load("maps", "2", {"callback": mapUmzug_Loaded});
}

function loadMaps_large() {
    google.load("maps", "2", {"callback": mapLarge_Loaded});
}

function sendMail() {
    // lock the page
    loading = true;
    // show "loading" indicator
    showIndicator(true);

    // check if all fields are set and send mail if so
    if( validateMailForm() ) {
        $('mailformer').action ="mailHandler.php";
        $('mailformer').set('send', {onComplete: function(response) {
            $('content').morph({opacity: [1.0, 0.0], duration: '500'});
            (function() {(
                    $('content').innerHTML = response
            )}).delay(500);
            (function() {(
                $('content').morph({opacity: [0.0, 1.0], duration: '1000'})
            )}).delay(500);
            new Tips($$('.tooltip'), { "timeOut": 700})
            // ... stop showing the "loading" indicator ...
            showIndicator(false);
            // realease the lock
            loading = false;
        }}).send();
    } else {
        // ... stop showing the "loading" indicator ...
        showIndicator(false);
        // realease the lock
        loading = false;
    }
}

function validateMailForm() {
    var name = $('fromName').value;
    var email = $('fromMail').value;
    var phone = $('phone').value;
    var response = 'E-Mail';
    for(i=0; i<$('mailformer').response.length; i++) {
        if($('mailformer').response[i].checked)
            response = $('mailformer').response[i].value;
    }
    var subject = $('subject').value;
    var text = tinyMCE.activeEditor.getContent();
    // update the value of the textarea (else php post variable may have wrong content)
    $('text').value = text;

    var result = true;
    var errormsg = '';

    // check name (not empty)
    if(name == '') {
        errormsg += 'Bitte geben Sie Ihren Namen in das Textfeld ein.\n';
        result = false;
    }
    // check subject
    if(subject == '') {
        errormsg += 'Bitte geben Sie einen Betreff für die Nachricht an.\n';
        result = false;
    }
    // check if the field given in response type is properly filled
    if(response == 'E-Mail') {
        var atPos = email.indexOf('@');
        var dotPos = email.lastIndexOf('.');
        // @ sign needs to be there and a dot behind @ and dot not as last sign
        if(atPos == -1 || dotPos <= atPos || dotPos == email.length) {
            errormsg += 'Sie haben keine oder eine ungültige E-Mailadresse angegeben.\n';
            result = false;
        }
    }
    if(response == 'Telefon') {
        if(phone == '') {
            errormsg += 'Sie haben keine Telefonnummer für unseren Rückruf angegeben.\n';
            result = false;
        }
    }
    // check the text for too many links ...
    var httpFound = 0;
    var maxHttp = 5;
    var i = text.indexOf('http://', 0);
    while( i != -1) {
        httpFound++;
        i = text.indexOf('http://', i+1);
    }
    if(httpFound > maxHttp) {
        errormsg += 'Sie haben zu viele Links auf Internetseiten in Ihrer Nachricht.\n';
        errormsg += 'Aus Sicherheitsgründen sind nicht mehr als '+maxHttp+' erlaubt.\n';
        result = false;
    }
    if(text=='') {
        errormsg += 'Sie haben keinen Inhalt für Ihre Nachricht angegeben.\n';
        result = false;
    }

    if(result == false) alert(errormsg);
    return result;
}

function mapSmall_Loaded() {
    var map = new google.maps.Map2($('map'));
    map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(52.013155,11.73524), 12);
    var point = new google.maps.LatLng(52.013155,11.73524);
    map.addOverlay(new google.maps.Marker(point));
    map.addControl(new google.maps.SmallMapControl());
}

function mapUmzug_Loaded() {
    var map = new google.maps.Map2($('map'));
    map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(52.013155,11.73524), 15);
    var point = new google.maps.LatLng(52.013155,11.73524);
    map.addOverlay(new google.maps.Marker(point));
    map.addControl(new google.maps.SmallMapControl());
}

function MapLarge_getBubbleHTML() {
    var text = '<div id="mapLargeBubble">';
    text += '<b>Praxis Seever</b><br>Jahnstraße 2<br>39218 Schönebeck (Elbe)<br><br>';
    text += '<b>Ihr Weg zu uns von:</b><br>';
    text += '<input type="text" value="Breiter Weg, Magdeburg" id="fromAdress" name="fromAdress" onFocus="$(\'fromAdress\').value=\'\';" length="50">';
    text += '<input type="button" value="Anzeigen" OnClick="mapLarge_setRoute();" /></div>';
    return text;
}

function mapLarge_Loaded() {
    mapLarge = new google.maps.Map2(document.getElementById("mapLarge"));
    mapLarge.enableScrollWheelZoom();
    mapLarge.setCenter(new GLatLng(52.013155,11.73524), 13);
    mapLarge.addControl(new google.maps.LargeMapControl());
    mapLarge.addControl(new google.maps.ScaleControl());
    mapLarge.addControl(new google.maps.MapTypeControl());
    mapLarge.addControl(new google.maps.OverviewMapControl());
    var loc = new google.maps.LatLng(52.013155,11.73524);
    var marker = new google.maps.Marker(loc);
    mapLarge.addOverlay(marker);
    GEvent.addListener(marker, "click", function() {
        mapLarge.openInfoWindowHtml(loc, MapLarge_getBubbleHTML());
    });
    mapLarge.openInfoWindowHtml(loc, MapLarge_getBubbleHTML());

    mapLargeRoute = new GDirections(mapLarge, document.getElementById("mapRoute"));
    google.maps.Event.addListener(mapLargeRoute, "error", MapLarge_handleErrors);
}

function MapLarge_handleErrors(){
    mapLargeRouteError = true;
    if (mapLargeRoute.getStatus().code != G_GEO_SUCCESS) {
        if(mapLargeRoute.getStatus().code == G_GEO_UNKNOWN_DIRECTIONS) {
            alert("Die Route konnte nicht berechnet werden.\n Überprüfen Sie bitte Ihre Eingabe.");
        } else if(mapLargeRoute.getStatus().code==G_GEO_TOO_MANY_QUERIES || mapLargeRoute.getStatus().code == G_GEO_BAD_KEY) {
            alert("Der Google Routenplaner ist nicht erreichbar.\n Bitte versuchen Sie es später     erneut.");
        } else {
            alert("Ihre Startadresse wurde nicht gefunden. Bitte überprüfen Sie Ihre Eingabe\n oder geben Sie weitere Details an (Straße, Hausnummer, PLZ, Stadt)");
        }
    } else {
        mapLargeRouteError = false;
    }
}

function mapLarge_setRoute() {
    var fromAdress = $('fromAdress').value;
    var toAdress = 'Jahnstraße 2, 39218, Schönebeck';
    mapLargeRoute.load("from: " + fromAdress + " to: " + toAdress, { "locale": 'de' });
    if(mapLargeRouteError==false) {
        //mapLarge.closeInfoWindow();
        var moveMapFX = new Fx.Elements($$('#mapLarge', '#mapRoute'), {duration: '1000'});
        moveMapFX.start({
            '0': {
                'left': [0, 360]
            },
            '1': {
                'width': [0, 350]
            }
        });
    }
    mapLargeRouteError = false;
}

function showIndicator(show) {
    if(show) {
        $('loader').style.visibility = 'visible';
    } else {
        $('loader').style.visibility = 'hidden';
    }
}

function fadeOut() {
    $('content').morph({opacity: [1.0, 0.0], duration: '1000'});
}

function fadeIn() {
    $('content').morph({opacity: [0.0, 1.0], duration: '1000'});
}

function maximizeContainer() {
    scaleContainer(viewportwidth-20, viewportheight-20);
}

function restoreContainer() {
    scaleContainer(768, 435);
}

function scaleContainer(newWidth, newHeight) {
    if(newWidth<minWidth) newWidth=minWidth;
    if(newHeight<minHeight) newHeight=minHeight;
    var elements = $$('#container', '#c_m', '#c_t_m', '#c_m_m', '#c_b_m');
    var ScaleContainerFX = new Fx.Elements(elements, {duration: '1000', link: 'chain'});
    ScaleContainerFX.start({
        '0': {
            'width': [oldWidth, newWidth],
            'height': [oldHeight, newHeight],
            'margin-left': [-1*oldWidth/2, -1*newWidth/2],
            'margin-top': [-1*oldHeight/2, -1*newHeight/2]
        },
        '1': {
            'height': [oldHeight-90-41, newHeight-90-41]
        },
        '2': {
            'width': [oldWidth-380-38, newWidth-380-38]
        },
        '3': {
            'width': [oldWidth-38-38, newWidth-38-38]
        },
        '4': {
            'width': [oldWidth-38-38, newWidth-38-38]
        }
    });
    oldWidth = newWidth;
    oldHeight = newHeight;
}

function getViewportSize() {
    // modern
     if (typeof window.innerWidth != 'undefined')
     {
          viewportwidth = window.innerWidth,
          viewportheight = window.innerHeight
     }
    // IE6
     else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientWidth !=
         'undefined' && document.documentElement.clientWidth != 0)
     {
           viewportwidth = document.documentElement.clientWidth,
           viewportheight = document.documentElement.clientHeight
     }
     // < IE6
     else
     {
           viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
           viewportheight = document.getElementsByTagName('body')[0].clientHeight
     }
}

var PulseFade = new Class({

  //implements
  Implements: [Options,Events],

  //options
  options: {
    min: 0,
    max: 1,
    duration: 200,
    times: 5
  },

  //initialization
  initialize: function(el,options) {
    //set options
    this.setOptions(options);
    this.element = $(el);
    this.times = 0;
  },

  //starts the pulse fade
  start: function(times) {
    if(!times) times = this.options.times * 2;
    this.running = 1;
    this.fireEvent('start').run(times -1);
  },

  //stops the pulse fade
  stop: function() {
    this.running = 0;
    this.fireEvent('stop');
  },

  //runs the shizzle
  run: function(times) {
    //make it happen
    var self = this;
    var to = self.element.get('opacity') == self.options.min ? self.options.max : self.options.min;
    self.fx = new Fx.Tween(self.element,{
      duration: self.options.duration / 2,
      onComplete: function() {
        self.fireEvent('tick');
        if(self.running && times)
        {
          self.run(times-1);
        }
        else
        {
          self.fireEvent('complete');
        }
      }
    }).start('opacity',to);
  }
});
