var flashIDs = new Array();
var showFlash = false;
var googleAnalyticsActive = 'false';
var keyvisAutoSkipTime=20000;
var keyvisTimer;
window.onload = init;

function switchBackground(obj, name) {
    var isOver = obj.getAttribute('isOver');
    if ((isOver == null) || (isOver == 'true')) {
        isOver = true;
    } else {
        isOver = false;
    }

    var astyle = obj.style;
    var img = obj.firstChild;
    astyle.backgroundImage = "none";
    img.src = "/get/params_W0/" + name;
    obj.setAttribute('isOver', (isOver ? 'false' : 'true'));
}                                                                            

function inputEmpty(event) {
    event = event ? event : window.event;
    var input = event.target ? event.target : event.srcElement;
    input.value = '';
}

function init() {
    var inputs = document.getElementsByTagName('input');

    for (i = 0; i < inputs.length; i++) {
        if ((inputs[i].type == 'text') && (inputs[i].value != '')) {
            if (
                    (inputs[i].name == 'phrase') ||
                    (inputs[i].name == 'username') ||
                    (inputs[i].name == 'password')
                    ) {
                inputs[i].onfocus = inputEmpty;
            }
        }
    }

    //    //buttons can only be clicked 1 time
    //    for(var i=0;i<inputs.length;i++){
    //		if(inputs[i].type=='submit'){
    //			inputs[i].onclick=Function("this.disabled='true';return true;");
    //		}
    //	}
    $('.featureArticle .teaserL .wrap .ct .flashClass').each(function(){
        //set the height of the wrap element and then remove the float:left;
        //otherwise the the result in IE is scrambled
       $(this).parent().parent().css('width',$(this).parent().parent().width());
       $(this).parent().parent().css('height',$(this).parent().parent().height()); 
       $(this).parent().parent().css('float','none');
    });

    if (showFlash) {
        for (var i = 0; i < flashIDs.length; i++) {
            if (document.getElementById("flashcontent_" + flashIDs[i])) {
                eval('so' + flashIDs[i]).write("flashcontent_" + flashIDs[i]);
                document.getElementById("flashcontent_" + flashIDs[i]).style.visibility = "visible";
            }
            if (document.getElementById("overlayflashcontent_" + flashIDs[i])) {
                eval('so' + flashIDs[i]).write("overlayflashcontent_" + flashIDs[i]);
            }
        }
    }

    tabs();
    if (typeof sitestatUrl == 'string') {
        sitestat(sitestatUrl);
    }

    //paging of flashmodules
    $('.keyvisPager a').each(function(){
        $(this).click(function (){
            $(this).blur();
            if(!$(this).hasClass('keyvisActive')){
                
                showKeyVis($('.keyvisPager a').index(this));    
            }
            return false;
        });
    });

    //check if keyvis list starts with an image (not a flash)
    if($('#keyvisWrap').length){
        if (!$('#AREA_keyvisual .flashClass').length) {
           keyvisTimer = window.setTimeout('showNextKeyVis()', keyvisAutoSkipTime);            
        }

    }
}

/**** start: COMMON ***/
// Basic function 2 swap / add / delete & check classes
// http://ichwill.net/cssjsseparation.html
function jscss(a, o, c1, c2)
{
    switch (a) {
        case 'swap':
            o.className = !jscss('check', o, c1) ? o.className.replace(c2, c1) :
                          o.className.replace(c1, c2);
            break;
        case 'add':
            if (!jscss('check', o, c1)) {
                o.className += o.className ? ' ' + c1 : c1;
            }
            break;
        case 'remove':
            var rep = o.className.match(' ' + c1) ? ' ' + c1 : c1;
            o.className = o.className.replace(rep, '');
            break;
        case 'check':
            return new RegExp('\\b' + c1 + '\\b').test(o.className)
            break;
    }
}

// Basic function 2 get Elements by class
// http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(node, searchClass, tag) {

    var classElements = new Array();
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b" + searchClass + "\\b");
    for (i = 0,j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}
function showFoo() {
    var el = getElementsByClass(document, 'foo', '*');
    alert(el.length);
}
/**** end: COMMON ****/

/**** start: TABS ***/
// *** needed files: common.js

// initial function
function tabs() {
    var node = 'container';
    var searchClass = 'tabfolder';
    var tag = '*';

    var elementArray = new Array();

    try {
        elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
    }
    catch (e) {
        node = 'textPopupContainer';
        try {
            elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
        }
        catch(ex) {
        }
        ;

    }
    ;

    for (var i = 0; i < elementArray.length; i++) {
        elementArray[i].setAttribute("id", "tabfolder" + i);
        var elemID = elementArray[i].id;
        addJSToTabs(elemID, i);
        addIDToTablinks(elemID);
        addIdToTabs(elemID);
    }
}

function ifJSprepareElements(parentID) {
    editClass(parentID, 'jsHideFirst', '*', 'swap', 'jsHideFirst', 'hide'); // hides Elements if JS is on
    editClass(parentID, 'jsHighlight', '*', 'swap', 'jsHighlight', 'hi'); // highlights active link if JS is on
}

function switchTab(TabNumber, funcParam) {
    var ParentFolder = 'tabfolder' + funcParam;
    var TabName = (ParentFolder + '_tabLink' + TabNumber);
    var TabHi = (ParentFolder + '_tab' + TabNumber);
    editClass(ParentFolder, 'hi', '*', 'swap', 'hi', 'lo');  // change hi-link to lo-link (node,searchClass,tag,classAction,class2swap,classSwapElem)
    jscss('add', document.getElementById(TabName), 'hi', '');  // change this link to hi-link
    editClass(ParentFolder, 'tab', '*', 'add', 'hide', ''); // hide all tab contents
    jscss('remove', document.getElementById(TabHi), 'hide', ''); // show this tab content
    try {
        IndicateTabsInSitestat(TabName); // indicate Tab per sitestat, if implemented
    } catch (e) {
    }
}

function addIdToTabs(elemID) {
    var node = elemID;
    var searchClass = 'tab';
    var tag = '*';
    var elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
    for (var i = 0; i < elementArray.length; i++) {
        elementArray[i].setAttribute("id", elemID + "_tab" + i);
    }
}

function addIDToTablinks(elemID) {
    var node = elemID;
    var searchClass = 'tablink';
    var tag = '*';
    var elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
    for (var i = 0; i < elementArray.length; i++) {
        elementArray[i].setAttribute("id", node + "_tabLink" + i);
        var elemID = elementArray[i].id;
    }
}

function editClass(node, searchClass, tag, classAction, class2swap, classSwapElem) {
    var elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
    for (var i = 0; i < elementArray.length; i++) {
        jscss(classAction, elementArray[i], class2swap, classSwapElem)
    }
}

function editClassById(id, classAction, class2swap, classSwapElem) {
    jscss(classAction, document.getElementById(id), class2swap, classSwapElem);
}

function addJSToTabs(elemID, funcParam) {
    addJsToElements(elemID, 'switchTab', funcParam); // (parentID,functionToAdd)
    ifJSprepareElements(elemID); // (parentID)
}

function addJsToElements(parentID, functionToAdd, funcParam) {
    if (document.getElementById &&
        document.getElementsByTagName) {
        var node = parentID;
        var searchClass = 'tablink';
        var tag = '*';
        var elementArray = getElementsByClass(document.getElementById(node), searchClass, tag);
        for (var i = 0; i < elementArray.length; i++) {
            elementArray[i].onclick = Function(functionToAdd + "(" + i + "," + funcParam + "); return false;");
        }
    }
}
/**** end: TABS ***/


function openPopup(anchor) {

    startPageTracker(anchor);
    var targetText = anchor.getAttribute('target');
    var linkText = anchor.getAttribute('href');
    if (targetText == 'text') {
        actualWindow = window.open(linkText, targetText, 'width=697px,height=650px,left=20px,top=20px,scrollbars=yes');
        actualWindow.focus();
        return false;
    }

    if (targetText == 'multimedia') {
        actualWindow = window.open(linkText, targetText, 'width=984px,height=650px,left=20px,top=20px,scrollbars=no');
        actualWindow.focus();
        return false;
    }

    if (targetText == 'popup') {
        actualWindow = window.open(linkText, targetText, 'width=980px,height=375px,left=20px,top=20px,scrollbars=no');
        actualWindow.focus();
        return false;
    }
}

function openFlexiblePopup(anchor, optional){
    startPageTracker(anchor);
    var targetText = anchor.getAttribute('target');
    var linkText = anchor.getAttribute('href');   
    actualWindow = window.open(linkText, targetText, ''+optional+'');
    actualWindow.focus();
    return false;
}

/*Submit Rollovers*/

function submit_colorvar(obj) {
    //colorScheme is set in meta.jsp
    $(obj).toggleClass(colorScheme + 'Hi');
}


function submit_blue_hi(instanz) {
    var instanz = instanz;
    /*alert ("er ist drin "+instanz);*/
    instanz.style.backgroundColor = '#003399';
    instanz.style.color = '#FFF';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_next_hi_blue_blue.gif)';
    return true;
}
function submit_blue_lo(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = 'transparent';
    instanz.style.color = '#010101';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_next_lo_blue_white.gif)';
    return true;
}
function submit_blue_grey_lo(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = 'transparent';
    instanz.style.color = '#010101';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_next_blue_grey.gif)';
    return true;
}


function submit_black_hi(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = '#000000';
    instanz.style.color = '#fff';
    instanz.style.backgroundImage = 'none';
    return true;
}
function submit_black_lo(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = 'transparent';
    instanz.style.color = '#666';
    instanz.style.backgroundImage = 'url(/general/img/color_variations/color_default/icons/ic_arrow_right_black_white.gif)';
    return true;
}
function submit_black_black_lo(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = 'transparent';
    instanz.style.color = 'rgb(1,1,1)';
    instanz.style.backgroundImage = 'url(/general/img/color_variations/color_default/icons/ic_arrow_right_black_white.gif)';
    return true;
}


function submit_white_hi(instanz) {
    var instanz = instanz;
    instanz.parentNode.style.backgroundColor = '#fff';
    instanz.style.color = '#000';
    instanz.style.backgroundImage = 'none';
    return true;
}
function submit_white_lo(instanz) {
    var instanz = instanz;
    instanz.parentNode.style.backgroundColor = 'transparent';
    instanz.style.color = '#fff';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_arrow_right_white_grey.gif)';
    return true;
}

function submit_up_blue_hi(instanz) {
    var instanz = instanz;
    /*alert ("er ist drin "+instanz);*/
    instanz.style.backgroundColor = '#003399';
    instanz.style.color = '#fff';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_up_hi_blue_blue2.gif)';
    return true;
}

function submit_up_blue_grey_lo(instanz) {
    var instanz = instanz;
    instanz.style.backgroundColor = 'transparent';
    instanz.style.color = '#010101';
    instanz.style.backgroundImage = 'url(/general/img/icons/ic_up_lo_blue_light_blue.gif)';
    return true;
}

/**** start: GLOSSARY ****/
function addRuleToStyleSheet(styleSheet, rule) {
    if (styleSheet.insertRule) styleSheet.insertRule(rule, styleSheet.cssRules.length);
    else if (styleSheet.addRule) styleSheet.addRule(rule.substring(0, rule.indexOf("{")), rule.substring(rule.indexOf("{") + 1, rule.indexOf("}")));
}

function toggleGlossary(anchor) {


    var div = anchor.parentNode.nextSibling;
    if (anchor.parentNode.nextSibling.nodeName != 'DIV') div = div.nextSibling;

    var toggle = div.getAttribute('toggle');
    if (toggle == 'true') {
        anchor.style.fontWeight = 'normal';
        anchor.style.backgroundImage = 'url(/general/img/color_variations/color_default/icons/ic_arrow_right_black_white.gif)';
        div.style.display = 'none';
        div.setAttribute('toggle', 'false');
    } else {
        anchor.style.fontWeight = 'bold';
        anchor.style.backgroundImage = 'url(/general/img/icons/ic_arrow_down_black_white.gif)';
        div.style.display = 'block';
        div.setAttribute('toggle', 'true');
    }
}

addRuleToStyleSheet(document.styleSheets[0], "#glossary_content .glossary_teaser .content {display:none;}");
addRuleToStyleSheet(document.styleSheets[0], "#glossary_content .glossary_teaser .headline span {cursor:pointer;font-size:0.75em;background-position:0px 50%;background-repeat:no-repeat;color:#010101;padding:1px 10px 1px 15px;text-decoration:none;background-image:url(/general/img/color_variations/color_default/icons/ic_arrow_right_black_white.gif); font-weight: normal;}");
/**** end: GLOSSARY ****/

/*** start: Toggle for product listing compare ***/

function uncheckAll() {

    var objForm = document.forms['compareFromListingForm'];
    var formElements = objForm.elements;

    for (var j = 0; j <= formElements.length; j++) {
        if (formElements[j])
            if (formElements[j].type == 'checkbox' && formElements[j].checked == true)
            //formElements[j].checked = false;
                formElements[j].parentNode.parentNode.parentNode.previousSibling.parentNode.style.borderColor = 'rgb(0,0,0)';
    }
}

function toggle(divId) {
    // need to toggle the element

    var elHighlite = document.getElementById(divId);
    // var targetNode = 5;
    var defaultColor = 'rgb(0,0,0)';
    var colorHi = 'rgb(178, 178, 178) rgb(178, 178, 178) rgb(178, 178, 178) rgb(178, 178, 178)';
    var version = navigator.appName;


    if (version == 'Microsoft Internet Explorer') {
        colorHi = 'rgb(178,178,178)';
        // targetNode = 3;
    }


    if (elHighlite.style.borderColor == colorHi || elHighlite.style.borderColor == '') {
        elHighlite.style.borderColor = defaultColor;
    } else {
        elHighlite.style.borderColor = colorHi;
    }

    /*
     var elHighlite = document.getElementById(divId);
     var targetNode = 5;
     var defaultColor = 'rgb(0,0,0)';
     var colorHi = 'rgb(178, 178, 178) rgb(178, 178, 178) rgb(178, 178, 178) rgb(178, 178, 178)';
     var version = navigator.appName;


     if (version == 'Microsoft Internet Explorer') {
     colorHi = 'rgb(178,178,178)';
     targetNode = 3;
     }


     if (elHighlite.childNodes[targetNode].style.borderColor == colorHi || elHighlite.childNodes[targetNode].style.borderColor == '') {
     elHighlite.childNodes[targetNode].style.borderColor = defaultColor;
     } else {
     elHighlite.childNodes[targetNode].style.borderColor = colorHi;
     }
     */
}
/*** end: Toggle for product listing compare ***/

function isExternalLink(externalLink){
    var isExternal=false;
    var myPort = (document.location.port!='') ? ':'+document.location.port : '';
    var myUrl=document.location.protocol+'//'+document.location.hostname+myPort+'/';
    if(externalLink.indexOf('http')!=-1){
        //alert('externalLink.substring: '+externalLink.substring(0,myUrl.length)+'\n'+'myurl: '+myUrl);
        if(externalLink.substring(myUrl.length)!=myUrl){
          isExternal=true;  
        }
    }
    return isExternal;
}

/* TRACKING */

function startPageTracker(anchor) {
    //this function is called by onclick events in a link element (a)
    //check if GA
    if (googleAnalyticsActive == 'true' && googleAnalyticsWebPropertyId != '') {
        var linkText = anchor.getAttribute('href').replace('/to\?exlink=', '').replace('/file\?filelink=', '');
        //check if external link
        if (isExternalLink(linkText)) {
            //alert('startPageTracker: '+linkText);
            pageTracker._trackPageview(linkText);
        }
    }
}

function startFileTracker(anchor) {
    //this function is called by onclick events in a link element (a) which downloads a file
    //check if GA
    if (googleAnalyticsActive == 'true' && googleAnalyticsWebPropertyId != '') {
        var linkText = anchor.getAttribute('href');
        linkText = linkText.substring(linkText.indexOf('elid=') + 5);
        linkText = linkText.substring(0, linkText.indexOf('&'));
       $.ajax({
            type: "GET",
            url: "/gafile",
            data: ({elid: linkText}),
            async: false,
            success: function(msg) {
                //alert('startFileTracker elid: '+linkText+' '+msg);
                pageTracker._trackPageview(msg);
                //alert("Data Saved: " + msg);
            }
        });
    }
}

/* Generate sitestat-code for video tracking */
function generateVideoTracking(nedstatName, countryCode) {
//    alert('generateVideoTracking - nestatName: '+nedstatName+' \ncountryCode: '+countryCode);
    var nedstatNameArr = nedstatName.split("/");
    nedstatName = nedstatNameArr[nedstatNameArr.length - 1];
    nedstatName = nedstatName.replace(/\./g, "_");
    var countryCodeArr = countryCode.split("_");
    var languageCode = countryCodeArr[0];
    var countryCode = countryCodeArr[1];
    var countryCodeLow = countryCode.toLowerCase();
    if (countryCodeLow == "gb") {
        countryCodeLow = "uk";
    }
    var timestamp = new Date().getTime();
    var actUrl = document.URL;
    var actUrlArr = actUrl.split("?");
    actUrl = actUrlArr[0];
    var nedstatUrl = escape("http://int.sitestat.com/panasonic/" + countryCodeLow + "/s?FlashVideo." + nedstatName + "." + countryCode + "." + languageCode + "&ns__t=" + timestamp + "&ns_referrer=" + actUrl);
    //	var nedstatUrl = "/general/html/pages/jsp/statisticHelper.jsp?trackUrl="+escape("http://int.sitestat.com/panasonic/"+countryCodeLow+"/s?FlashVideo."+nedstatName+"."+countryCode+"."+languageCode+"&ns__t="+timestamp+"&ns_referrer="+actUrl);
    return nedstatUrl;
}

/* YOUTUBE */

function startVideoTracker(counterName) {
    //this function is used by youtube video and video from galleries
   // START: Sitestat Tracking
    //alert('startFlashTracking:(Sitestat) ' + unescape(generateVideoTracking(counterName,locale)));
        var nsImage=new Image();
        nsImage.src=unescape(generateVideoTracking(counterName,locale));
   // END: Sitestat Tracking
   // START: Google Analytics Tracking    
    //check if GA is activated
    if (googleAnalyticsActive == 'true' && googleAnalyticsWebPropertyId != '') {
        //alert('startFlashTracking:(Google Analytics) ' + counterName);
        pageTracker._trackPageview('FlashVideo.'+counterName+'.'+countycode+'.'+languagecode);
    }
   // END: Google Analytics Tracking      

}

var flashmoviePlayersStartCounter=new Array(); // associative array ["countername"] - contains how ofter a player is started;
var flashmoviePlayersCounterName=new Array(); // associative array ["countername"] - contains the countername for the flashmovie;

function onYouTubePlayerReady(playerId) {
    //alert('youtubeready_playerid_: '+playerId);
    var player = $('#myytplayer' + playerId)[0];
    player.addEventListener('onStateChange', '(function(state) { return playerState(state, "' + playerId + '"); })');
}

function playerState(state, playerId) {
    if (state == 1) {
        //check if counter exists
        if (typeof(flashmoviePlayersStartCounter[playerId]) == "undefined") {
            flashmoviePlayersStartCounter[playerId] = 1;
        } else {
            //if already exists then increase
            flashmoviePlayersStartCounter[playerId]++;
        }
        // only start tracking, if status is "starting" and counter==1
        if(flashmoviePlayersStartCounter[playerId]==1){
            //alert('started ' + playerId + ' count: ' + flashmoviePlayersStartCounter[playerId]);
          startVideoTracker(flashmoviePlayersCounterName[playerId]);  
        }
    }
}

function onPlayerError(errorCode) {
    //alert("An error occured: " + errorCode);
}

function showNextKeyVis() {
    //check if there are more than one keyvis(flash)
    if ($('.keyvisPager a').length) {
        var pagePos = $('.keyvisPager a.keyvisActive');
        pagePos = $('.keyvisPager a').index(pagePos);
        // alert(pagePos);
        if (pagePos == ($('.keyvisPager a').length) - 1) {
            pagePos = 0;
        } else {
            pagePos++;
        }
        showKeyVis(pagePos);
    }
}

function showKeyVis(keyvisPagerIndex) {
    if (typeof(keyvisTimer) != 'undefined') {
        window.clearTimeout(keyvisTimer);
    }
    $('.keyvisPager a.keyvisActive').removeClass('keyvisActive');
    $('.keyvisPager a').eq(keyvisPagerIndex).addClass('keyvisActive');
    $.get('/html/'+locale+'/'+pageId+'/flash.html', { keyvisIndex: keyvisPagerIndex, useLayout: 'keyVis' }, function(data) {
        //alert(data);
        $('#keyvisWrap').replaceWith(data);                  
        //check if it flash or an image
        if ($('#AREA_keyvisual .flashClass').length) {
            var newFlashId = $('.keyvis').attr('id');
            newFlashId = newFlashId.substring(newFlashId.indexOf('_') + 1);
            eval('so' + newFlashId).write("flashcontent_" + newFlashId);
            document.getElementById("flashcontent_" + newFlashId).style.visibility = "visible";
        }
        else {
            keyvisTimer = window.setTimeout('showNextKeyVis()', keyvisAutoSkipTime);
        }
        //check overlay flash
        if ($('#keyvisOverlay .flashClass').length) {
            var newOverlayFlashId = $('.keyvisoverlay').attr('id');
            //alert(newOverlayFlashId);
            newOverlayFlashId = newOverlayFlashId.substring(newOverlayFlashId.indexOf('_') + 1);
            eval('so' + newOverlayFlashId).write("overlayflashcontent_" + newOverlayFlashId);
            //document.getElementById("overlayflashcontent_" + newOverlayFlashId).style.visibility = "visible";
        }
        //because IE Browser has problem of z-index, the style of z-index must be added for 'RANGE_head' by displaying of overlay flash. By closing overlay flash, the additional style must be removed.
        if (document.getElementById('RANGE_head').getAttribute('style') != 'undefined') {
        document.getElementById('RANGE_head').removeAttribute('style');
    }

    });
}


