/*	autor:	(c) jens enkhardt
 *		file:	jquery_animations.js
 *		info:	jquery animations css styles
 */
var autoAnimation = false; //false by default. It will be updatet inside of div#imageBox
var animationInterval = 3000; //Interval to call the animation funtion. Default is 3000 ms
var contentType = "unknown";

// InfoBox Vars
var bIsInfoBoxOpen = false; //hold the status of the infobox (open/close)
var bInfoBoxAnimationInProgress = false; //is the infobox just animated?
// ImageGroup Vars
var ConteinerOfImages = new Array(); //array of imageGroups
var currentImageGroupNR = 0; //active imageGroup Nr
// textGroup Vars
var ContainerOfTextGroups = new Array(); //array of textGroups
var currentTextGroupNR = 0; //active textGroup Nr
// newsboxes Vars
var countOfNewsBoxes = 0; //count of div.news-latest-item
var currentNewsBoxStartID = 0; //child nr of active news item. Only 3 news items are visible.
//this var saves the child ID of the first visible news box. (0 = 0,1,2)

// ----------------------------------------------------

$(document).ready(function(){
    //thickbox is coming-give the udm a new z-index
    $('ul#udm').css("z-index", "90");
    
    //check ImageGroup for more images
    checkImageGroup();
    
    checkTextGroup();
    
    checkNewsCount();
    
    //check, if autoAnimation should be start
    if (autoAnimation == true) {
        //alert("AutoAnimation = true!");
        imageAnimation();
    }
    else {
        //alert("AutoAnimation = false");
    }
    
    //arrow left:click
    $('a#preImg').click(function(){
        if (contentType == "imageGroup") {
            //alert("contentType = imageGroup");
            getAndSetPreviosImageGroup();
        }
        if (contentType == "textGroup") {
            //alert("contentType = textGroup!");
            showTextGroupNr(currentTextGroupNR - 1);
        }
        if (contentType == "news") {
            //alert("contentType = news!");
            showNewsBoxesFromBoxNr(currentNewsBoxStartID - 3);
        }
        
        
        return false;
    });
    
    //arrow right:click
    $('a#nextImg').click(function(){
        //imageGroup
        if (contentType == "imageGroup") {
            getAndSetNextImageGroup();
        }
        if (contentType == "textGroup") {
            //alert("contentType = textGroup!");
            showTextGroupNr(currentTextGroupNR + 1);
        }
        if (contentType == "news") {
            //alert("contentType = news!");
            showNewsBoxesFromBoxNr(currentNewsBoxStartID + 3);
        }
        return false;
    });
});

// -----------------------------------------------------

//image animation
function imageAnimation(){
    //alert("imageAnimation()!");
    showImageGroupNr(currentImageGroupNR + 1);
    window.setTimeout("imageAnimation()", animationInterval);
}

// -----------------------------------------------------

//open the infobox:
function openInfoBox(){
    if (bIsInfoBoxOpen == false && bInfoBoxAnimationInProgress == false) {
        bInfoBoxAnimationInProgress = true;
        
        //remove the infobox button:
        $('a#infoBoxButton').remove();
        
        //set opacity for the infoBox:
        $('div#infoBox').css('opacity', '0.8');
        
        //set a new infobox label:
        $('div#useLinks ul li:eq(1)').html('<span id="infoBoxButtonDisabled" style="color:#ccc;">Info</span>');
        
        //starts the infobox animaion:
        $('div#infoBox').animate({
            "right": "20px"
        }, "slow");
        
        bIsInfoBoxOpen = true;
        bInfoBoxAnimationInProgress = false;
        
        return false;
    }
}

//close the infobox:	
function closeInfoBox(){
    if (bIsInfoBoxOpen == true && bInfoBoxAnimationInProgress == false) {
        bInfoBoxAnimationInProgress = true;
        
        //remove the infobox button:
        $('span#infoBoxButtonDisabled').remove();
        
        //set a new infobox label:
        $('div#useLinks ul li:eq(1)').html('<a onclick="openInfoBox()" id="infoBoxButton" style="cursor: pointer;">Info</a>');
        
        //starts the infobox animaion:
        $('div#infoBox').animate({
            "right": "-240px"
        }, "slow");
        
        bIsInfoBoxOpen = false;
        bInfoBoxAnimationInProgress = false;
        
        return false;
    }
    
}

// -----------------------------------------------------

//get and set previos image group
function getAndSetPreviosImageGroup(){
    showImageGroupNr(currentImageGroupNR - 1)
}

//get und set next image group
function getAndSetNextImageGroup(){
    showImageGroupNr(currentImageGroupNR + 1);
}

// check image Group for more images
function checkImageGroup(){
    //alert("checkImageGroup()...");
    
    //check start images
    var imageBox = $('div#imageBox').length;
    //check if imageBox is ariviable
    if (imageBox == 0) {
        //alert("Error: imageBox not found!");
        return; //exit
    }
    contentType = "imageGroup";
    //save first images in array (standard images)
    ConteinerOfImages[0] = new Object();
    ConteinerOfImages[0]["big"] = $('div#image_big img#imgLeft').attr('src');
    ConteinerOfImages[0]["small"] = $('div#image_small img#imgRight').attr('src');
    
    //check rest of images
    var anzImgBig = $('div#ListsOfContentImages ul#left li').length;
    var anzImgSmall = $('div#ListsOfContentImages ul#right li').length;
    
    if ((anzImgBig == 0) || (anzImgSmall == 0)) {
        // alert("Error: no another images was set!");
        return; //exit
    }
    
    //check if count of big and small images are the same
    if (anzImgBig != anzImgSmall) {
        //alert("Error:	Big and Small images haven't the same count!");
        return; //exit
    }
    
    //current ImageGroup Nr is 1 (first start images)
    currentImageGroupNR = 0;
    
    //set another images in the array
    var maxImg = anzImgBig;
    delete anzImgBig;
    delete anzImgSmall;
    for (var i = 0; i < maxImg; i++) {
        ConteinerOfImages[i + 1] = new Object();
        ConteinerOfImages[i + 1]["big"] = $('div#ListsOfContentImages ul#left li:eq(' + i + ')').html();
        ConteinerOfImages[i + 1]["small"] = $('div#ListsOfContentImages ul#right li:eq(' + i + ')').html();
    }
    
    setImageGroup(ConteinerOfImages.length); //show and set ImageGroup Links
    $('div#browseImages span#imgPages a#0').attr('class', 'act'); //set group 0 as active	
    //if autoAnimation is disabled, show the arrows
    if (autoAnimation == false) {
        showArrows(); //show arrows	
    }
}

// set imageGroup Number
function setImageGroup(imageNr){
    var imgPages = $('span#imgPages');
    var imgPagesValue = "";
    var linkValue = "";
    
    
    for (var i = 0; i < imageNr; i++) {
        linkValue = '<a href="#" id="' + i + '" onclick="showImageGroupNr(' + i + '); this.setAttribute(\'class\', \'act\'); return false;">' + (i + 1) + '</a>';
        imgPagesValue += linkValue;
    }
    //alert("imgPagesValue = " + imgPagesValue);
    imgPages.html(imgPagesValue);
    imgPages.attr('style', 'display:block;visibility:visible;');
}

// show the image arrows (left and right)
function showArrows(){
    var arrowLeft = $('div#arrow_left');
    var arrowRight = $('div#arrow_right');
    var visibleCSS = "display:block;visibility:visible;";
    arrowLeft.attr('style', visibleCSS);
    arrowRight.attr('style', visibleCSS);
}

// show imageGroup Nr
function showImageGroupNr(nr){
    $('span#imgPages a.act').removeClass("act"); //remove the existing class="act" attr
    bigImage = $('img#imgLeft');
    smallImage = $('img#imgRight');
    
    if (nr == -1) {
        nr = (ConteinerOfImages.length - 1);
    }
    else 
        if (nr > (ConteinerOfImages.length - 1)) {
            nr = 0;
        }
    
    $("span#imgPages a:eq(" + nr + ")").attr("class", "act"); //set new class="act" attribute
    bigImage.attr('src', ConteinerOfImages[nr]["big"]);
    smallImage.attr('src', ConteinerOfImages[nr]["small"]);
    
    currentImageGroupNR = nr;
    
    return false;
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

function validateName(name){
    if (name.val().length < 4) {
        name.addClass("error");
        name.focus();
        return false;
    }
    else {
        name.removeClass("error");
        return true;
    }
}

function validateEmail(emailStr){
    var emailPat = /^(.+)@(.+)$/
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validChars = "\[^\\s" + specialChars + "\]"
    var quotedUser = "(\"[^\"]*\")"
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom = validChars + '+'
    var word = "(" + atom + "|" + quotedUser + ")"
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$")
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$")
    var matchArray = emailStr.match(emailPat)
    if (matchArray == null) {
        //alert("Die Email-Adresse scheint fehlerhaft zu sein!")
        return false
    }
    var user = matchArray[1]
    var domain = matchArray[2]
    if (user.match(userPat) == null) {
        //alert("Der Teil vor dem @-Zeichen scheint fehlerhaft zu sein!")
        return false
    }
    var IPArray = domain.match(ipDomainPat)
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                //alert("Destination IP address is invalid!")
                return false
            }
        }
        return true
    }
    var domainArray = domain.match(domainPat)
    if (domainArray == null) {
        //alert("Der Teil nach dem @-Zeichen scheint fehlerhaft zu sein!")
        return false
    }
    var atomPat = new RegExp(atom, "g")
    var domArr = domain.match(atomPat)
    var len = domArr.length
    if (domArr[domArr.length - 1].length < 2 ||
    domArr[domArr.length - 1].length > 6) {
        //alert("The address must end in a top level domain (e.g. .com), or two letter country.")
        return false
    }
    if (len < 2) {
        var errStr = "This address is missing a hostname!"
        //alert(errStr)
        return false
    }
    return true;
}

function validateUrl(url){
    var Exp = /cmo-architekten.+/;
    //var Exp = /osw/;
    if (url.search(Exp) != -1) {
        return true;
    }
    else {
        return false;
    }
}


function validateForm(lang){
    var language = lang;
    var iErrors = 0;
    var name = $('input#form_name');
    var email = $('input#form_email');
    var url = $('input#form_url');
    
    name.removeClass("error");
    email.removeClass("error");
    
    //alert("name = " + name.val() +	"email = " + 	email.val() + "url = " + 	url.val() );
    
    if ((name.val() == null) || (name.val() == "")) {
        iErrors++;
        name.focus();
        name.addClass("error");
    }
    if ((email.val() == null) || (email.val() == "")) {
        iErrors++;
        email.focus();
        email.addClass("error");
    }
    if ((url.val() == null) || (url.val() == "")) {
        iErrors++;
    }
    
    if (iErrors == 0) {
    
        if (!validateName(name)) {
            iErrors++;
            name.addClass("error");
            name.focus();
        }
        if (!validateEmail(email.val())) {
            iErrors++;
            email.addClass("error");
            email.focus();
        }
        if (!validateUrl(url.val())) {
            iErrors++
            alert("ALERT: HACK DETECTED!\nYou want to suggest another site like this one!\nPlease inform the admin 'info@cmo-architekten.de!");
        }
    }
    
    if (iErrors == 0) {
        //alert("Keine Fehler gut so!");  
        $.ajax({
            url: 'fileadmin/templates/inc/tipafriend.php?lang=' + language,
            type: 'POST',
            data: {
                Name: name.val(),
                Email: email.val(),
                Url: url.val(),
                PostTime: getDateAndTime(),
                Language: language
            },
            success: function(neueDaten){
                $('div#container_form div#result').html(neueDaten);
                $('div#container_form div#result').fadeIn("slow");
            }
        });
        
    }
    else {
        //alert("FEHLER: " + iErrors);
        return false;
    }
}

function getDateAndTime(){
    var Jetzt = new Date();
    var Tag = Jetzt.getDate();
    var Monat = Jetzt.getMonth() + 1;
    var Jahr = Jetzt.getYear();
    var Stunden = Jetzt.getHours();
    var Minuten = Jetzt.getMinutes();
    var NachVoll = ((Minuten < 10) ? ":0" : ":");
    if (Jahr < 2000) {
        Jahr = Jahr + 1900;
    }
    return Tag + "." + Monat + "." + Jahr + "-" + Stunden + NachVoll + Minuten + "h";
}

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

//check, if textGroup as content are ariviable
function checkTextGroup(){
    //check if textTextBox is present
    if ($('div#textTextBox').length != 1) {
        //alert("No textTextBox found! :(");
        return;
    }
    else {
        contentType = "textGroup";
        //alert("Anzahl an div.content: " + $('div#textTextBox div.content').length );	
        //if more than 1, then show arrows
        if ($('div#textTextBox div.content').length > 1) {
            //show arrow buttons
            showArrows();
        }
        
        for (var i = 0; i < $('div#textTextBox div.content').length; i++) {
            ContainerOfTextGroups[i] = $('div#textTextBox div.content[' + i + ']');
        }
        
        //show the first textGrup!
        showTextGroupNr(0);
    }
}


// show textGroup Nr
function showTextGroupNr(nr){
    //hide all textGroup Box:
    $('div#textTextBox div.content').attr("style", "display:none;");
    if (nr == -1) {
        nr = (ContainerOfTextGroups.length - 1);
    }
    else 
        if (nr > (ContainerOfTextGroups.length - 1)) {
            nr = 0;
        }
    $("div#textTextBox div.content:eq(" + nr + ")").attr("style", "display:block;"); //show the x textBox
    currentTextGroupNR = nr;
    
    
    //show SIFR
    sIFR.replace(architect, {
        selector: 'div#textTextBox div.innerTextTop h1',
        css: ['.sIFR-root {color:#FFFFFF; font-size:22px; }'],
        wmode: 'transparent',
        ratios: [6, 1.24, 7, 1.21, 8, 1.18, 10, 1.16, 19, 1.13, 31, 1.08, 44, 1.06, 57, 1.05, 58, 1.04, 69, 1.05, 112, 1.04, 114, 1.03, 1.04]
    });
    
    return false;
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

function checkNewsCount(){
    //check if newsboxes are present
    if ($('div.news-latest-container').length != 1) {
        // alert("No news found! :(");
        return;
    }
    else {
        contentType = "news";
        //alert("Anzahl an div.news-latest-item: " + $('div.news-latest-container div.news-latest-item').length);
        //if more than 3, then show arrows
        if ($('div.news-latest-container div.news-latest-item').length > 3) {
            //show arrow buttons
            showArrows();
            //hide all newsboxes:
            hideAllNewsBoxes();
        }
        countOfNewsBoxes = $('div.news-latest-container div.news-latest-item').length;
        
        //show the first three textboxes	
        showNewsBoxesFromBoxNr(0);
    }
}

//set newsboxes with nr (boxNr,boxNr+1,boxNr+2) visible
function showNewsBoxesFromBoxNr(boxNr){
    //hide all newsboxes:
    hideAllNewsBoxes();
    for (var i = 0; i < 3; i++) {
        actBox = (boxNr + i);
        
        if (actBox > countOfNewsBoxes) {
            //$('div#arrow_right a').attr("style", "display:none;");
            $('div#arrow_right a').css({ "display":"none" });
        }
        else {
            $('div#arrow_right a').attr("style", "display:inline;");
        }
        if (boxNr == 0) {
            $('div#arrow_left a').attr("style", "display:none;");
        }
        else {
            $('div#arrow_left a').attr("style", "display:inline;");
        }
        
        $('div.news-latest-container div.news-latest-item:eq(' + actBox + ')').attr("style", "display:block;");
        
        
    }
    
    currentNewsBoxStartID = boxNr;
    //        alert("currentNewsBoxStartID = " + (currentNewsBoxStartID));  
}

function hideAllNewsBoxes(){
    $('div.news-latest-container div.news-latest-item').attr("style", "display:none;");
}

