/**
* functions.js
*
* Contains common functions used in the whole page
* @author Benny Born <benny@bennyborn.de>
* @version 1.0
*/

/**
* creates a new xmlHTTP object
* @returns object
**/
function getXMLHttpObject() {

	var xmlHttp;

	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {

		try {
			// Microsoft Internet Explorer
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {

				return null;
			}
		}
	}

	return xmlHttp;
}


/**
* converts seconds to hours, minutes and seconds
* @param numSecs Number of seconds
* @returns string
**/
function sec2hms( numSecs ) {

    var timeStr = '';

    var hh     = parseInt(numSecs / 3600);
    var ssr    = (numSecs-(hh*3600));
    var mm     = parseInt(ssr / 60);
    var ss     = (ssr - (mm * 60)); 

    timeStr = str_pad(hh,2,'0','STR_PAD_LEFT')+':'+str_pad(mm,2,'0','STR_PAD_LEFT')+':'+str_pad(ss,2,'0','STR_PAD_LEFT');

    return timeStr;
}


/**
* prints out an object or array (equivalent to the php function)
* @param arr The array / object to print
* @param level The level (must be 0)
* @returns String
**/
function print_r( arr,level ) {

    var dumped_text = "";

    if(!level) level = 0;

    var level_padding = "";

    for(var j=0;j<level+1;j++) level_padding += "    ";

    // array / objects
    if( typeof(arr) == 'object' ) {

        for( var item in arr ) {

            var value = arr[item];
 
            if( typeof(value) == 'object' ) {

                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += print_r(value,level+1);

            } else {

                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else {
        
        // strings / chars / numbers...
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }

    return dumped_text;
}


/**
* equivalent to phps function
* @param input The input string
* @param pad_length The final length
* @param pad_strin The string to fill the input with
* @param pad_type The pad type STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH
**/
function str_pad( input, pad_length, pad_string, pad_type ) {

    var half = '', pad_to_go;

    var str_pad_repeater = function(s, len) {
        var collect = '', i;

        while(collect.length < len) collect += s;
        collect = collect.substr(0,len);

        return collect;
    };

    input += '';

    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }
        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);
        }
    }

    return input;
}


/**
* rotates the newsticker to the next position
* @returns void
**/
function tickTicker() {

    tOffset = Obj.offsetWidth / 3;

    if(Math.abs( tPos ) > tOffset) {
        tPos = 0;
    }

    Obj.style.left = tPos + 'px';
    tPos = parseInt( tPos ) - tPixel;
}


/**
* starts the newsticker
* @param tNews Array containing the lines to tick on
* @param tDelimiter String containing a delimiter for the lines
* @returns void
**/
function runTicker( tNews,tDelimiter ) {
    
    if( tNews == '' || tDelimiter == '' )
        return false;

    appName     = "unbekannt";
    appVersion  = "unbekannt";

    UA = navigator.userAgent.toLowerCase();

    // IE
    if(UA.search(/msie/) != -1) {
        appName = "IE";
        appVersion = parseFloat(/(msie[^;]*)/.exec(UA)[0].split(" ")[1]);
    }
    // Opera
    else if(UA.search(/opera/) != -1) {
        appName = "Opera";
        appVersion = parseFloat(/(opera[^\s]*)/.exec(UA)[0].split("/")[1]);
    }
    // Firefox
    else if(UA.search(/firefox/) != -1) {
        appName = "Firefox";
        appVersion = parseFloat(/(firefox[^\s]*)/.exec(UA)[0].split("/")[1]);
    }
    // Safari
    else if(UA.search(/khtml/) != -1) {
        appName = "Safari (Win)";
        appVersion = parseFloat(/(version[^\s]*)/.exec(UA)[0].split("/")[1]);
    }

    switch ( appName ) {

        case "Firefox": {
            switch ( appVersion )
            {
                case 2: default:
                {
                    tInterval = 150;
                    tPixel = 10;
                }
                break;
            }
        }
        break;
        
        case "Opera":
        case "IE":
        case "Safari (Win)":
        default: {
            tInterval = 100;
            tPixel = 10;
        }
        break;
    }
    
    
    tStop = true;

    IE  = document.all&&!window.opera;
    DOM = document.getElementById&&!IE;

    if( DOM || IE ) {

        tPos  = 0;
        tStop = tStop?'onmouseover="clearInterval(tGo)"' + 'onmouseout="tGo=setInterval(\'tickTicker()\',' + tInterval + ')"':'';
        tTxt  = tDelimiter + tNews.join( tDelimiter );
        tNews = tTxt;
    
        for(i = 1; i < 3; i++) {
            tNews += tTxt;
        }
        
        document.write('<div style="overflow:hidden;width: 100%;height: 15px; background-color: #000;">' +
        '<div style="width: 100%;height: 20px;overflow: hidden;clip: rect(0px 700px 20px 0px);">' +
        '<span id="ticker" style="white-space: nowrap;position: relative;" ' + tStop + '>' + tNews + '</span>' +
        '</div>' +
        '</div>');

        Obj = IE ? document.all.ticker : document.getElementById('ticker');
    }
}


/**
* opens a vote-popup
* @param voteID The id of the vote to open
* @returns none
**/
function showVote( voteID ) {

    if( voteID == '' )
        return false;

	var oVoteWin = null;
 
    oVoteWin = window.open("/vote/?voteID="+voteID, '', "width=350,height=600,status=no,scrollbars=no,resizable=yes");
    oVoteWin.focus();
}


var currRating = 1;
var ratingDone = false;


/**
* changes the star images for the selected rating
* @param rating A rating from 1 to 5
* @returns none
**/
function setRating( rating ) {

    if( rating < 1 || rating > 5 || ratingDone )
        return false;

    currRating = rating;

    for( var i=1; i<=5; i++ ) {

        var obj = document.getElementById('rating'+i);

        if( i > rating )
            obj.src = '/gfx/core/ratingicons/star_small_empty.png';
        else
            obj.src = '/gfx/core/ratingicons/star_small_full.png';
    }
}


/**
* sends a rating request over ajax
* @param ratingID The id of the rating
* @returns bool
**/
function submitRating( ratingID ) {

    if( ratingID == '' || currRating == 0 || ratingDone )
        return false;

    var xmlHTTP     = getXMLHttpObject();
    
    xmlHTTP.onreadystatechange = function() {

        if( xmlHTTP.readyState == 4) {

            ratingDone = true;
            alert("Vielen Dank für Deine Bewertung");
        }
    }

    xmlHTTP.open("GET","/meta/doRating.php?id="+ratingID+"&r="+currRating,true);
    xmlHTTP.send(null);
}


/**
* retrieves the users giga premium data
* @returns bool
**/
function getGIGAPremiumData() {

    var xmlHTTP     = getXMLHttpObject();
    
    xmlHTTP.onreadystatechange = function() {

        if( xmlHTTP.readyState == 4) {

            return true;
        }
    }

    xmlHTTP.open("GET","/meta/getGIGAPremiumData.php",true);
    xmlHTTP.send(null);
}


/**
* create a jw-player with some default configs
* @param divID The ID of the div where to create the player in
* @param videoURL The url of the video
* @param videoType The type of the video (GFD,GIGA OR YT)
* @param addPlayerVars Object with additional player configs to overwrite the defaults
**/
function showVideoPlayer( divID, videoURL, videoType, addPlayerVars  ) {

    // initialize player vars
    var playerVars          = new Object();
    playerVars.file         = videoURL;

    // set layout
    playerVars.controlbar   = 'over';
    playerVars.backcolor    = '#000000';
    playerVars.frontcolor   = '#FFFFFF';
    playerVars.lightcolor   = '#178C00';

    // set behaviour
    playerVars.width        = '350';
    playerVars.height       = '260';
    
    // set right-click
    var oDate               = new Date();
    playerVars.abouttext    = '&copy; 2004 - ' +oDate.getFullYear()+ ' GIGAfoundation.de';
    playerVars.aboutlink    = 'http://www.gigafoundation.de/impressum/';


    // merge player vars
    if( addPlayerVars ) {

        for( varName in addPlayerVars ) {
            playerVars[varName] = addPlayerVars[varName];
        }
    }

    // set special behaviour for special video types
    // (gfd, giga, yt)
    if( videoType ) {

        switch( videoType.toUpperCase() ) {

            // GIGAfoundation videos
            case 'GFD'  :
                playerVars.logo = '/gfx/core/player/logo_gfd.png';
            break;

            // GIGA videos
            case 'GIGA'  :
                playerVars.logo = '/gfx/core/player/logo_giga.png';
            break;

            // YouTube videos
            case 'YT'  :
            
                playerVars.stretching   = 'none';
                var clipID = videoURL.substr(31);

                if( clipID )
                    playerVars.image = 'http://i2.ytimg.com/vi/'+clipID+'/hqdefault.jpg';

                playerVars.link = videoURL;
            break;
        }
    }

    // create player
    var s1 = new SWFObject('/js/core/player/player.swf','player',playerVars.width,playerVars.height,'9');
    s1.addParam('allowfullscreen','true');
    s1.addParam('allowscriptaccess','always');

    var flashvars = '';
    for( varName in playerVars )
        flashvars += '&'+varName+'='+playerVars[varName];

    s1.addParam('flashvars',flashvars);
    s1.write(divID);
}


/**
* generates a flash tagcloud
* containing the usernames of users that
* are online now
**/
function loadUserTagCloud( ) {

    var xmlHTTP     = getXMLHttpObject();
    
    xmlHTTP.onreadystatechange = function() {

        if( xmlHTTP.readyState == 4 ) {

            var tagsXML = xmlHTTP.responseText;

            // create tagcloud
            if( tagsXML != '' ) {

                var so = new SWFObject("/flash/cumulus/tagcloud.swf", "tagcloud", "224", "200", "7", "#000000");
                so.addParam("wmode", "transparent");
                so.addVariable("tcolor", "0x333333");
                so.addVariable("tcolor2", "0x009900");
                so.addVariable("hicolor", "0x178C00");
                so.addVariable("tspeed", "100");
                so.addVariable("mode", "tags");
                so.addVariable("tagcloud", tagsXML);
                so.write("userTagCloud");
            }
        }
    }

    xmlHTTP.open("GET","/meta/getUserTagCloud.php",true);
    xmlHTTP.send(null);
}