/**
 * Name: tsipMain.js
 * Author: hte
 * Description: Standard-Javascript Bibliothek fuer TSI - Plattform
 * 
 * Date: 16.08.2010
 * Packed: no 
 * jQuery: yes
 * Use CSS: no
 */

// CSS-Klasse, welche nur bei eingeschalteten Javascript geladen wird
document.write("<link rel=\"stylesheet\" href=\"/tsip/servlet/contentblob/doc/un/v1-2011-script-css.css/blobBinary/v1-2011-script-css.css\" type=\"text/css\" media=\"screen\"/>");

/** auszufuehrende Events bei Laden der Seite * */
jQuery(document).ready(function () {
  TsipMain.init();
});

jQuery(window).load(function () {
  TsipMain.fixTabs();
});

/** Konstantendefinitionen  */
var TsipMainConstants = {
  CSS_CONT_ON: "on",    // Container aufgeklappt
  CSS_CONT_OFF: "off"   // Container zugeklappt
};

/** Bibliotheksdefinition */
var TsipMain = {
    
    /** Array und Variablendefinitionen  */
    /** arrayName1: [
          TsipMainConstants.KONSTANTE_1,
          TsipMainConstants.KONSTANTE_3
        ],
    */             
    colsArr: [], // Array fuer die Hoehenberechnung von Containern                   
   
    /** Funktionsdefinitionen */
               
    /**
     * Initialisierungsmethode
     */
    init: function() {
      try { TsipMain.calculateBoxHeight(); } catch(ex) {/* nothing */}
      try { TsipMain.initSitemap(); } catch(ex) {/* nothing */}
    },
    
    // Funktion prueft auf ein gueltiges E-Mail Format
    checkEmail: function(email) {
      var proto = "(mailto:)?";
      var usr = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
      var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
      var regex = "^" + proto + "?" + usr + "\@" + domain + "$";
      var rgx = new RegExp(regex);
      return rgx.exec(email) ? true : false;
    },

    /**
     * Boxenhoehe auf einer Zeile, jQuery erforderlich
     * Array wird am Anfang initialisiert und nach jedem col-Div, 
     * was mehr als ein Element enthaelt mit ID befuellt
     */
    calculateBoxHeight: function() {
      for (var i = 0; i < TsipMain.colsArr.length; ++i) {
        h = 0;
        count = 0;
        // Boxen, die mit .noCalc markiert sind, bekommen keine Hoehe
        divName     = "div#" + TsipMain.colsArr[i] + " > div:not(.noCalc) > div";
        divName_sbL = "div#" + TsipMain.colsArr[i] + " > div:not(.noCalc) > div > div.sbL";
        divName_bN  = "div#" + TsipMain.colsArr[i] + " > div.bN:not(.noCalc) > div > div.sbL";
        jQuery(divName).each(function(i) {
          if(this.offsetHeight > h) {
            h = this.offsetHeight;
          }
          count++;
        });
        if(count > 1) {  
          // TransitionGrids
          if (jQuery(divName).parent().parent().attr("class") == "transitionBox row") {
            h = h + 3;
          }
          jQuery(divName).css("height",h);
          jQuery(divName_sbL + " > div.sV").css("height",h-42);
          // Boxen ohne Containertitle
          if(h-13 > 42) {
            jQuery(divName_sbL + " > div.noT").css("height",h-13);
          } else {
            jQuery(divName_sbL + " > div.noT").css("height",42);
          }
          // NullBoxen
          jQuery(divName_bN + " > div.noT").css("height","100%");
        }
      }
    },
    
    /**
     * Funktion prueft auf ein gueltiges E-Mail Format
     */
    checkEmail: function(email) {
      var proto  = "(mailto:)?";
      var usr    = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
      var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
      var regex  = "^" + proto + "?" + usr + "\@" + domain + "$";
      var rgx    = new RegExp(regex); 
      return rgx.exec(email) ? true : false;
    },
    
    /**
     * Funktion prüft anhand des Namens den verwendeten Browser 
     */
    checkBrowserName: function(bName) {
       var agent = navigator.userAgent.toLowerCase();
       if (agent.indexOf(bName.toLowerCase()) > -1) {
          return true;
       }  
       return false;
    },

    /**
     * Methode prueft  
     */
    stringEndsWithIgnoreCase: function(s, suffix) {
      compare = s.substring(s.length-suffix.length).toLowerCase();
      suffix = suffix.toLowerCase();
      //alert(compare==suffix);
      return (compare==suffix);
    },
    
    /**
     * SelectBox welche auch Popups anzeigt
     */
    fctSelectList: function(value) {
      if (!value || value=="") return;
      value = value.split("|");
      if (value.length>1) {
        var modify = value[1].split(",");
        switch (modify[0]) {
          //workaround f. ie7 sicherheits feature, im popup ist die sicherheitswarnung nicht zu sehen,
          //deshalb werden zip dateien im selben fenster geoeffnet
          case "_blank": if (TsipMain.stringEndsWithIgnoreCase(value[0], "zip")) { t = "_self";} else {t = "_blank";} window.open(value[0],t);break;
          //case "_blank": window.open(value[0],"_blank");break;
          case "top": top.location.href=value[0];break;
          case "parent": parent.location.href=value[0];break;
          default:
            if (isNaN(modify[0]) && top.frames[modify[0]])
              top.frames[modify[0]].location.href=value[0];
            else if (!isNaN(modify[0])) {
              //600,500,0,0,1,0,1,printversion
              if (modify.length<8) {
                if (top.frames["mainframe"])
                  top.frames["mainframe"].location.href=value[0];
                else self.location.href=value[0];
              }  else {
                TsipMain.fctOpenWin(value[0],modify[0],modify[1],modify[2],modify[3],modify[4],modify[5],modify[6],modify[7]);
              }
            } else if (!top.frames[modify[0]]) self.location.href=value[0];
          }
       } else if (top.frames["mainframe"])
           top.frames["mainframe"].location.href=value[0];
         else 
           self.location.href=value[0];
       // EventTracker
       if (value.length > 2) {
         etValues = value[2].split(">");
         etName = "";
         etTags = "";
         if (etValues.length >= 0) etName = etValues[0];
         if (etValues.length >= 1) etTags = etValues[1];
         ET_Event.download(etName, etTags);
       }
    },
    
    /*
     * Helper-Funktionen
     */
    positionHelper: function(param,position) {
      if (param<0) return 0;
      if (window.screen) {
        if (param>window.screen.availHeight && position=="top") return 0;
        if (param>window.screen.availWidth && position=="left") return 0;
      }
      return param;
    },
    sizeHelper: function(param,min) {
      if (isNaN(min)) min=200;
      if (isNaN(param) || param < min) return min;
      return param;
    },
    booleanHelper: function(param) {
      //if (isNaN(param)) return 0;
      if (isNaN(param)) {
        if(param=="true") return "yes"; else return "no";	
      }
      if (param<=0) return "no"; else return "yes";
    },
    getCleanedString: function(param) {
      param = String(param).replace(/\W/gi,"");
      return param;
    },
    changeLocationHelper: function(url,obj) {
      obj.location.replace(url);
    },
    locationCompareURL: function(actURL,newURL) {
      return !(actURL==newURL);
    },
    
    /**
     * Popup oeffnen
     */
    fctOpenWin: function(resource,height,width,top,left,blnScrollbar,blnResizable,blnMenubar,targetname) {
    
      targetname = TsipMain.getCleanedString(targetname);
      
      if( targetname=="") targetname = "MyWindow";
      
      height=TsipMain.sizeHelper(height);
      width=TsipMain.sizeHelper(width);
      top=TsipMain.positionHelper(top,"top");
      left=TsipMain.positionHelper(left,"left");
      blnScrollbar=TsipMain.booleanHelper(blnScrollbar);
      
      blnResizable=TsipMain.booleanHelper(blnResizable);
      blnMenubar=TsipMain.booleanHelper(blnMenubar);
      F = window.open(resource,targetname,"height="+height+",width="+width+",menubar="+blnMenubar+",resizable="+blnResizable+",scrollbars="+blnScrollbar+",left="+left+",top="+top);
      if (F.focus) F.focus();
  },
  
  /**
   * Methode realisiert Container-Klappmechanismus
   */
  switchContStatus: function(idContainer) {
    contObj = jQuery("#"+idContainer);
    if(jQuery(contObj).hasClass(TsipMainConstants.CSS_CONT_ON)){
      jQuery(contObj).removeClass(TsipMainConstants.CSS_CONT_ON).addClass(TsipMainConstants.CSS_CONT_OFF);
    } else if (jQuery(contObj).hasClass(TsipMainConstants.CSS_CONT_OFF)) {
      jQuery(contObj).removeClass(TsipMainConstants.CSS_CONT_OFF).addClass(TsipMainConstants.CSS_CONT_ON);
    }
  },
 
  /**
   * Methode schaltet den Sichtbarkeitstatus eines  Containers um.
   * @param obj: Objekt, auf welches die Methode aufgerufen wird (meist 'this')
   * @param txtOne: Text 1
   * @param txtTwo: Text 2
   * @param idSwitchContainer: Container, welcher aus-/eingeblendet werden soll.
   */
  switchContStatusLabel: function(obj, txtOne, txtTwo, idSwitchContainer) {
    txtToChange = jQuery(obj).html();
    if(txtToChange == txtOne) {
     jQuery(obj).html(txtTwo);
    } else if(txtToChange == txtTwo) {
     jQuery(obj).html(txtOne);
    }
    TsipMain.switchContStatus(idSwitchContainer);
  },
  
  /**
   * Methode initialisiert die Sitemap
   */
  initSitemap: function() {
    smObjs = jQuery("ul.sitemaptree");
    if(smObjs.length > 0) {
      jQuery(smObjs).treeview({
        animated: "fast",
        collapsed: true
      });
    };
  },
  
  /**
   * Methode realisiert Ajax-Request
   */
  getReqByAjax: function(targetUrl,targetDiv) {
    jQuery(document).ready(function(){
      jQuery.ajax({
        url: targetUrl,
        cache: true,
        success: function(html){
          document.getElementById(targetDiv).innerHTML = html;
          TsipMain.evalScript(html);
        }
      });
    });
    document.getElementById(targetDiv).scrollIntoView(true);
  },
  
  /**
   * Methode realisiert Ajax-Request, wenn Video-Container vorhanden ist
   */
  getReqByAjaxForVideo: function(targetUrl,containerId) {
    try	{
	  if ((typeof videoDetailContainerUrl != 'undefined') && (typeof videoDetailContainerId != 'undefined')) {
        TsipMain.getReqByAjax(targetUrl,'ajax_' + containerId);
        document.getElementById('cm' + containerId).scrollIntoView(true);
      }
	} catch(e) {
      // href ausfuehren
	  window.location.href = $(element).attr("href");
    }
  },

 /**
  * fuehrt JS in Ajax-Requests aus
  */
  evalScript: function(scripts) {
    try	{	
      if(scripts != '')	{	
        var script = "";
        scripts = scripts.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
            if (scripts !== null) script += arguments[1] + '\n';
            return '';});
        if(script) (window.execScript) ? window.execScript(script) : window.setTimeout(script, 0);
      }
      return false;
    }	catch(e) {
      alert(e)
    }
  },
  
  /**
   * Gibt den Print-Button aus
   */
  writePrintButton: function(targetDiv, label) {
    var html = "<a href=\"#\" onclick=\"window.print()\"><span>" + label + "</span></a>";
    document.getElementById(targetDiv).innerHTML = html;
  },
  
  /**
   * Laedt externes JS innerhalb der Seite nach
   */
  loadExtJavaScript: function(targetDiv, src) {
    var oScript = document.createElement("script");
    oScript.src = src;
    document.getElementById(targetDiv).appendChild(oScript);
  },

  /**
   * gibt eine Zufallszahl mit angegebener Laenge aus
   */
   getRandom: function(length) {
     r=String(Math.random());
     str=r.substring(2,2+length);
     return str;
   },
   
   /**
   * IE-Fix fuer Ueberlagung bei Tab-Boxen
   */
   fixTabs: function() {
    // MC
    jQuery("#vidActions.tabBox").parent().parent().removeClass("sV").addClass("sV");
    // eingebettete Tabs
    jQuery(".paG .tabBox").parent().removeClass("sV").addClass("sV");
    // Tagbereiche in M-Boxen
    jQuery(".tags").parent().children(".sV").removeClass("sV").addClass("sV");
    //jQuery(".box .sV:not(#footerArea .sV)").removeClass("sV").addClass("sV");
   }
};
