////////////
//					 				 JavaScript Functions									  //
//											ver. 2.0										  //
//										Author: Alex Kvak									  //
////////////

// initializing a browser
var aks_isIE=0,aks_isNN=0, aks_isMF=0;
if (navigator.userAgent.indexOf("Firefox")!=-1) aks_isMF=1;
if	(document.all) 
	aks_isIE=1;
else 
	if(document.layers) 
		aks_isNN=1;
var aks_isOpera = (navigator.userAgent.indexOf("Opera") > 0);
//////////////////////////////

//////////////////////////////
/*
	Sets active OPTION in SELECT element
	@param tag_id 	id of the SELECT element
	@param value 	value of OPTION element to be selected
*/
//////////////////////////////
function aks_set_select_value(tag_id,value)
{
	if (!(obj = my$(tag_id))) return false;
	if (obj.options) {
		var lo_len = obj.options.length;
		var lo = obj.options;
	
		for(i=lo_len-1;i>=0;i--)
			if (lo[i].value == value)
			{
				lo[i].selected = true;
				break;
			}
		return true;
	}
	return false;
}
//////////////////////////////

//////////////////////////////
function aks_suredelete(obj)
{
    val_ = confirm(suredelete_confirm);
    if (val_== false) return false;
    obj.action_.value='delete';
    return true;
}
//////////////////////////////

//////////////////////////////
function aks_suredeleteAktuell(obj)
{
    val_ = confirm(suredelete_confirm);
    if (val_== false) return false;
    obj.action_.value='delete_aktuell';
    return true;
}
//////////////////////////////

//////////////////////////////
function aks_suredelete_rubrik(obj)
{
    return confirm(suredelete2_confirm);
}
//////////////////////////////

//////////////////////////////
function aks_sureoben(obj)
{
    val_ = confirm(sureoben_confirm);
    if (val_== false) return false;
    obj.action_.value='oben';
    return true;
}
//////////////////////////////

//////////////////////////////
function aks_sureunten(obj)
{
    val_ = confirm(sureunten_confirm);
    if (val_== false) return false;
    obj.action_.value='unten';
    return true;
}
//////////////////////////////

//////////////////////////////
// return Element by Id 
function aks_getElement(n)
{
   return my$(n);
}
//////////////////////////////

//////////////////////////////
// return Element by Id 
function my$(n)
{
   if (typeof document.getElementById(n) != "undefined")
	   return document.getElementById(n);
   else
   	   return false;
}
//////////////////////////////

//////////////////////////////
// creates a popUp
/*
function aks_popupWnd(url,title,width,height,scrollbars)
{
   if (title == "random")
   	 title = "wnd"+(Math.ceil(Math.random() * 10)).toString();
	 
   var options = "status=off,menubar=off,height="+height+",width="+width;
   var xtop = (screen.height-height)/2-15, xleft = (screen.width-width)/2;
   options += ",top="+xtop+",left="+xleft;
   
   if ( (scrollbars == "on") || (scrollbars == true) )
   	options += ",scrollbars=1";
   else
   	if (scrollbars == "auto")
		options += ",scrollbars=1";
	else
	   	options += ",scrollbars=0";
   
   var popup = window.open(url,title,options); 
   popup.document.close();
   return popup;
}
*/
function aks_popupWnd(url) {
    $().jOverlay({url: url, imgLoading : 'bilder/ajax-loader.gif', autoHide : false, bgClickToClose : false});   
}
//////////////////////////////

//////////////////////////////
// changes the CheckBox flag of Element num
function aks_changeCheck(num)
{
	if (obj = aks_getElement(num))
		obj.checked = !obj.checked;
}
//////////////////////////////

//////////////////////////////
// set the display property of Element num
function aks_setView(num, show)
{
	var obj = aks_getElement(num);
	if (obj) obj.style.display = (show) ? '':'none';
}
//////////////////////////////

//////////////////////////////
// set the visibility of Element num	
function aks_setVisibility(num, show)
{
	var obj = aks_getElement(num);
    obj.style.visibility = (show) ? "visible":"hidden";
}
//////////////////////////////

//////////////////////////////
// returns the display property of Element num			
function aks_getView(num)
{
    var obj = aks_getElement(num);
    return obj.style.display;
}
//////////////////////////////

//////////////////////////////
// changes the visibility ogf Element num		
function aks_changeView(num)
{
    visibility_ = aks_getView(num);
	show = (visibility_ == 'none') ? true : false;
	aks_setView(num, show);
	return true;
}
//////////////////////////////

//////////////////////////////
// sets the color farbe to all cells of table row obj
function aks_setFarbe(obj,farbe)
{
    theCells = obj.cells;
    var rowCellsCnt = theCells.length;
    for (c = 0; c < rowCellsCnt; c++) 
        theCells[c].style.backgroundColor=farbe;
}
//////////////////////////////

//////////////////////////////
// sets the color farbe to specified cell obj
function aks_setFarbeCell(obj,farbe)
{
     obj.style.backgroundColor = farbe;
}
function sF(obj,farbe) {
     aks_setFarbeCell(obj,farbe)
}
//////////////////////////////

//////////////////////////////
// sets the color farbe to specified cell obj
function aks_goToURL(url)
{
     location.href = url;
}

function go(url) {
     aks_goToURL(url);
}
//////////////////////////////

/* CROSS-BROWSER EVENT HANDLER */
    function addEvent(obj, evType, fn){
         if (obj.attachEvent){
             var r = obj.attachEvent("on"+evType, fn);
            return r;
         } else if (obj.addEventListener){
             obj.addEventListener(evType, fn, true);
             return true;
         } else {
            return false;
         }
    }
	
    
function aks_checkSuche(field,value) {
    return ((my$(field).value!='') && (my$(field).value!=value));
}


////////////
// creates a new popUp window for changing the properties 
function aks_configPopUp()
{
	aks_popupWnd("edit_config.php","configPopUp",500,550,true);
	return false;
}
////////////

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function gallery(img,titel) { document.images["bigest"].src = 'i/g/'+img; document.images["bigest"].alt = titel; } 
function showGallery(index) {
    if (gImages) {
        iIndex = index;
        img = gImages[iIndex].i;
        titel = gImages[iIndex].t;
        gallery(img,titel);
        aks_setView('TRtxt',false);
        aks_setView('TRbild',true);
        
        pos = cumulativeOffset(my$('TRbild'));
        window.scrollTo(pos[0], pos[1]);

        if (my$('bildTitel')) my$('bildTitel').innerHTML = titel;
    }
    return false;
}

function showGallery_fade(index) {
    if (gImages) {
        iIndex = index;
        
        my$('TRbigest').style.backgroundImage = 'url(bilder/lade_bild.gif)'; 
        $('#bigest').css('visibility', 'hidden');
        
        img = gImages[iIndex].i;
        titel = gImages[iIndex].t;
        gallery(img,titel);
        
        preloadImage(gImages, iIndex);
//        $('#bigest').fadeIn(1000); 
        
        if (my$('bildTitel')) my$('bildTitel').innerHTML = titel;
    }
    return false;
}

function doFade(obj) {
    obj.parentNode.style.backgroundImage = 'url(bilder/leer.gif)';
    $(obj).css('visibility', 'visible');
    $(obj).hide().fadeIn(800);    
}

function hideGallery() {
    aks_setView('TRbild',false);
    aks_setView('TRtxt',true);
}

function cumulativeOffset (element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
}

function swst(obj,style) {if (obj) obj.className = style;} 

function focushandler(obj,str) {
    if (obj.value == str) obj.value = '';
}

function blurhandler(obj,str) {
    if (obj.value == '') obj.value = str;
}

function nextBild() {
    if (gImages) {
        if (++iIndex >= gImages.length) iIndex = 0; 
        showGallery(iIndex);
    }
}

function fillSelect(obj,von,bis,inc) {
    for (var y=von;y!=bis+inc;y+=inc) {
        var newOpt = new Option(y,y, false, false);
        obj.options[obj.options.length] = newOpt;
    }    
}

function fillSelect2(obj,array) {
    for (var i=0;i<array.length;i++) {
        var newOpt = new Option(array[i],i+1, false, false);
        obj.options[obj.options.length] = newOpt;
    }    
}

function initFormular(vals) {
    fillSelect(my$('anreise_tag'),1,31,1);
    fillSelect2(my$('anreise_monat'),['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember']);
    fillSelect(my$('anreise_jahr'),curYear,curYear+5,1);
    
    if (typeof vals != "undefined") {
        if (vals.anreise_tag) aks_set_select_value('anreise_tag',parseInt(vals.anreise_tag));
        if (vals.anreise_monat) aks_set_select_value('anreise_monat',parseInt(vals.anreise_monat));
        if (vals.anreise_jahr) aks_set_select_value('anreise_jahr',parseInt(vals.anreise_jahr));
    }
}

function pasteImageToEditor(src,width,height) {
    var oEditor = FCKeditorAPI.GetInstance('text_');
    if (!oEditor) return;
    
//    img = document.createElement('img');
//    img.setAttribute('src', src);
//    img.setAttribute('width', width);
//    img.setAttribute('height', height);
    oEditor.InsertHtml('<img src="'+src+'" width="'+width+'" height="'+height+'">');
}

function c(obj) {
    $('div[id^='+obj.attr('name').replace(/\d+$/,'')+']').show();
    c_ajax();
}

function c_ajax() {
    $('#result').html('Laden...');
    $('#result').load('ajax.php', $('#bestell_form').serialize());
    $('#bestellformular').val('0');
}

function clr(elem) {
    $(':input[name^='+elem.parentNode.id.replace(/_reset$/,'')+']').attr('checked', '');
    $('select[name^='+elem.parentNode.id.replace(/_reset$/,'')+']').find('option:first').attr('selected', 'selected').parent('select');
    $(elem.parentNode).hide();
    c_ajax();
}

function chkradio(name) {
//    var checked = false;
//    $(':input[name='+name+']').each(function() {
//        if ($(this).attr('checked')) checked = true;
//    });
    $(':input[name='+name+']:last').attr('checked','checked');
}

function submitBestellformular(frm) {
    var frmOK = true;
    $(frm).find('.pflicht').each(function() {
        if (frmOK && !$(this).val()) {
            alert('Füllen Sie bitte das Feld '+ ucwords($(this).attr('name')) +' ein');
            frmOK = false;
        }
    });
    
    if (frmOK) {
//        frm.action = '';
        $('#bestellformular').val('senden');
        c_ajax();
//        frm.submit();
    }
}

function ucwords(str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // *     example 1: ucwords('kevin van zonneveld');    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();    });
}

function showGalleryOben(index) {
    clearInterval(galleryIntervalID);
    
    if (gObenImages) {
        iIndex = index;
        document.images["bigestOben"].src = 'i/g/' + gObenImages[iIndex];
        
        // preloading next image
        if (++index >= gObenImages.length) index = 0;
        MM_preloadImages('i/g/' + gObenImages[index]);
    }
    return false;
}

function preloadImage(imagesArray, index) {
    if (++index >= imagesArray.length) index = 0;
    MM_preloadImages('i/g/' + imagesArray[index].f);
    
    if (++index >= imagesArray.length) index = 0;
    MM_preloadImages('i/g/' + imagesArray[index].f);
}

function blendImageOben() {
    clearInterval(galleryIntervalID);
    
    //set the current image as background

    my$('TRbildOben').style.backgroundImage = "url(" + my$('bigestOben').src + ")";
    
    //make image transparent
    $('#bigestOben').hide();
    $('#Layer4_2').hide();
    $('#Layer2_2').hide();
    
    if (++iIndex >= gObenImages.length) iIndex = 0;
    document.images["bigestOben"].src = 'i/g/' + gObenImages[iIndex].f;
    $('#TRbildOben a').attr('href', gObenImages[iIndex].l);
    
    $('#Layer4').html($('#Layer4_2').html()).fadeOut(500, function() {
        text = gObenImages[iIndex].u;
        if (gObenImages[iIndex].l) text = '<a href="'+gObenImages[iIndex].l+'">' + text + '</a>';
        $('#Layer4_2').html(text).fadeIn(500);
    });
    $('#Layer2').html($('#Layer2_2').html()).fadeOut(500, function() {
        text = gObenImages[iIndex].o;
        if (gObenImages[iIndex].l) text = '<a href="'+gObenImages[iIndex].l+'">' + text + '</a>';
        $('#Layer2_2').html(text).fadeIn(500);
    });
    
    preloadImage(gObenImages, iIndex);
    
    $('#bigestOben').fadeIn(1000, function () { 
        my$('TRbildOben').style.backgroundImage = 'url(bilder/leer.gif)'; 
        galleryIntervalID = setInterval('blendImageOben()', galleryInterval); 
    } );
} 

function chkFormular(frm) {
    var found = 0;
    $(frm).find('input.pflicht').each(function() {
        if (!found && !$(this).val()) {
            found = 1;
            $(this).focus();
            return;
        }
    });
    if (!found) {
        $(frm).find('input[name^="projekte"]').serialize();
        if (!$(frm).find('input[name^="projekte"]:checked').length) {
            alert('Sie haben kein Projekt ausgewählt');
            return false;
        }
        
        if (!$(frm).find('input[name=datum]').val().length) {
            alert('Sie haben kein Datum ausgewählt');
            return false;
        }
    }
    if (found) {
        alert('Sie haben nicht alle Pflichfelder eingefüllt!');
        return false;
    }
    
    return true;
}
