/**
 * Global JavaScripts
 */
var hasProductInstall = DetectFlashVer(6, 0, 65);
var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
var redirects;
var IE = /*@cc_on!@*/false;

/**
 * Document ready
 */
$(document).ready(function(){
    $('.pagination_new').css({'display': 'block'});
    $('#mode_online img').css({'display': 'block'});
    $('a.basic').cluetip({width: '448'});
    $(".model_thumb img:below-the-fold").lazyload({
        placeholder : "images/dating.jpg", 
        event : "sporty" 
    });

    if (IE) {
    //    theObjects = document.getElementsByTagName("object");
    //    for (var i = 0; i < theObjects.length; i++) {
    //        theObjects[i].outerHTML = theObjects[i].outerHTML;
    //    }
    }

    // Version check based upon the values defined in globals
    // Check to see if a player with Flash Product Install is available and the version does not meet the requirements for playback
    if (hasProductInstall && !hasRequestedVersion )
    {
        $('#ex').modal();
    }
    initNewsLetter();
});

function initNewsLetter() {
    
    if (basename() == 'index.php') {
        if (typeof(getCurrentPage()) != false) {
            ctrl = getCurrentPage();
        } else {
            ctrl = 'login';
        }
        popupbox('msgNewsletter', ctrl);
    }
}

function basename() {
    path = window.location.href.replace(/\\/g,'/').replace( /.*\//, '' );
    path = window.location.href.replace(/\\/g,'/').replace( /.*\//, '' );
    path = path.split('?');
    if (path[0] == '')
    path[0] = 'index.php';
    return path[0];
}

function getCurrentPage() {
    if (typeof(getVar('ctrl')) != 'undefined') {
        if (getVar('ctrl') == 'vodix') {
            if (getVar('type') == 'clip') {
                currentpage = 'freeclip';
            } else {
                currentpage = 'topclip';
            }
        } else {
            currentpage = getVar('ctrl');
        }
    } else {
        currentpage = 'login';
    }
    return currentpage;
}

document.close();
$(window).bind("load", function() { 
    var timeout = setTimeout(function() {$("img").trigger("sporty")}, 5000);
});

/**
 * Function Declarations
 */
function jah(url,target) {
    // native XMLHttpRequest object
    document.getElementById(target).innerHTML = '<div style="text-align:center;padding:25px;height:573px;"><img src="images/ajax-loader.gif" style="margin-top:250px;"/></div';
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {jahDone(target);};
        req.open("GET", url, true);
        req.send(null);
    // IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {jahDone(target);};
            req.open("GET", url, true);
            req.send();
        }
    }
}

function jahDone(target) {
    // only if req is "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            results = req.responseText;
            document.getElementById(target).innerHTML = results;
            recallTooltip();
        } else {
            document.getElementById(target).innerHTML="jah error:\n" +
                req.statusText;
        }
    }
    $('.pagination_new').css({'display': 'block'});
    $('#mode_online img').css({'display': 'block'});
    thumbnailOverlay();
}


// ajax request for Weitere Online Cams ( 9 )
function newOnlinemode()
{
    $.ajax({
        type: "POST",
        url: "index.php?ctrl=cam_list_ajax&mode=online&cat=null",
        data: "",
        cache: false,
        beforeSend: function(data) {
            $("#search_placeholder").html("<div class='loader_page'><img src='images/ajax-loader.gif'/></div>");
        },
        success: function(data) {
            $("#search_placeholder").html(data);
            $('a.basic').cluetip({width: '448'}); // load tooltip info
        }
    });
}

//ajax request for CHATPARTNER SUCHEN:
function searchCamlist(url)
{
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        cache: false,
        beforeSend: function(data) {
            $("#search_placeholder").html("<div class='loader_page'><img src='images/ajax-loader.gif'/></div>");
        },
        success: function(data) {
            $("#search_placeholder").html(data);
            $('a.basic').cluetip({width: '448'}); // load tooltip info
            
        }
    });
}

function getdata(url)
{
    $.ajax({
        type: "POST",
        url: url,
        data: "",
        cache: false,
        beforeSend: function(data) {
            $("#search_placeholder").html("<div class='loader_page'><img src='images/ajax-loader.gif'/></div>");
        },
        success: function(data) {
            $("#search_placeholder").html(data);
            $('a.basic').cluetip({width: '448'}); // load tooltip info
            thumbnailOverlay();
            clearTimeout(camlistRefresher);
        }
    });
}

/*
function msgbox(boxType) {
    $.ajax( { 
        type: "POST", 
        url: "index.php?ctrl=message&modal=true", 
        data: "msgType=" + boxType, 
        async: false
    } ).responseText;
    alert('INSIDE UNIVERSAL!');
}
*/

function recallTooltip() {
    var tmp_val = false;
    if (tmp_val == false) {
        $(document).ready(function() {
            //$('a.basic').cluetip({width: '448'});
            
                    $('a.basic').each(function() { 
                            $(this).cluetip('destroy'); 
                            //$(this).unbind().remove(); 
                    }); 

                    $('#cluetip*').unbind().empty(); 

                    $('a.basic').each(function() { 
                            $(this).cluetip({width: '448'}); 
                    }); 
            
            thumbnailOverlay();
        });
        tmp_val = true;
    }
}

msgbox = function(type, button, title, body, redirection){
    redirects = redirection;
    if (body.length > 100){
        frame = 'height=105&width=300';
    } else {
        frame = 'height=100&width=300';
    }
    $('#dump').load('index.php?ctrl=message',{ctrl: 'message', msgType: type, msgButton: button, msgDetailTitle: title, msgDetailBody: body, redirect: redirection},
        function(){
            tb_show(title, '#TB_inline?'+frame+'&inlineId=dump&modal=true', null);
        }
    );
}

popupbox = function(type, currentpage) {
    json = new Object();
    $.ajax({
        type: 'GET',
        url: 'index.php?ctrl=message&type=newsletterCheck&key='+currentpage,
        processData: true,
        data: {},
        dataType: 'json',
        cache: false,
        beforeSend: function() {

        },
        success: function(json) {
            if (typeof(json) != 'object') {
                return false;
            } else {
                if (json == null) { return false; }
                title = '';
                json['width'] = json['width'] - 30;
                frame = 'height='+json['height']+'&width='+json['width'];
                $('#dump').load('index.php?ctrl=message',{ctrl: 'message', image: json['imageurl'], msgType: type, id: json['id'] },
                    function(){
                        tb_show(title, '#TB_inline?'+frame+'&inlineId=dump&modal=true', null);
                    }
                );
            }
        },
        complete: function() {
        }
    });
}

cropAvatar = function(type, button, title, body, redirection) {
    redirects = redirection;
    $('#dump').load('index.php?ctrl=cropavatar',{ctrl: 'cropimage', msgType: type, msgButton: button, msgDetailTitle: title, msgDetailBody: body, redirect: redirection},
        function() {
            tb_show(title, '#TB_inline?height=600&width=730&inlineId=dump&modal=true', null);
        }
    );
}

function msgResponder(type)
{
    tb_remove();
    if (type == 'cancel')
    {
        return false;
    }
    if (type == 'ok')
    {
        if (typeof redirects != "undefined")
        {
            window.location = redirects;
        }
        return true;
    }
}

function utf8_decode ( str_data ) {
    var tmp_arr = [], i = ac = c1 = c2 = c3 = 0;

    str_data += '';

    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}

function in_array(string, array) {
    for(var i=0; i<array.length; i++)
    {
        if (array[i] == string) return true;
    }
    return false;
}

function getVar(urlVar) {
        var phpget = [];
        querystring = window.location.search.substring(1);
        arrays = querystring.split("&");
        getLength = arrays.length;
        for (i=0;i<getLength;i++) 
        {
            chunks = arrays[i];
            splitVars = chunks.split("=");
            getRef = splitVars[0];
            phpget[getRef] = splitVars[1];
        }
        return (typeof(phpget[urlVar])=="undefined")?false:phpget[urlVar];
}

function getImgSize(imgSrc)
{
    var newImg = new Image();
    img = {};
    newImg.src = imgSrc;
    img.Height = newImg.height;
    img.Width = newImg.width;
    return img;
}

function loadImageInGallery(image) {
    if (image)
    {
        $('#defaultModelPhoto').attr('src', image);
        $('#defaultModelPhotoButton').attr('href', image);
        imgOrig = getImgSize(image);
        data = getDimensionsScaled(imgOrig.Width, imgOrig.Height, 298, 298);
        if (data.width)
        {
            $('#defaultModelPhoto').attr('style', 'width: '+data.width+'px; height: '+data.height+'px;');
        }
    }
    //return data;
}

function getDimensionsScaled(width, height, targetWidth, targetHeight, upscale){
    img = {};
    if (((width > targetWidth) && (height > targetHeight)) || ((upscale) && (width <= targetWidth) && (height <= targetHeight))) {
        widthFac  = targetWidth / width;
        heightFac = targetHeight / height;
        if (widthFac < heightFac) {
            imgWidth  = targetWidth;
            imgHeight = (height * widthFac);
        } else {
            imgWidth  = (width * heightFac);
            imgHeight = targetHeight;
        }
    } else if (width > targetWidth) {
        widthFac  = targetWidth / width;
        imgWidth  = targetWidth;
        imgHeight = (height * widthFac);
    } else if (height > targetHeight) {
        heightFac = targetHeight / height;
        imgWidth  = (width * heightFac);
        imgHeight = targetHeight;
    } else {
        img.width = Math.ceil(width);
        img.height = Math.ceil(height);
        return img;
    }
    img.width = Math.ceil(imgWidth);
    img.height = Math.ceil(imgHeight);
    return img;
}




function _getFlash(mc)
{
//alert("_getFlash called");
    if (window.document[mc]) 
    {
        return window.document[mc];
    }
    if (navigator.appName.indexOf("Microsoft Internet") == -1)
    {
        if (document.embeds && document.embeds[mc]) return document.embeds[mc]; 
    }
    else
    {
        return document.getElementById(mc);
    }
}

function _callFlashMethod(methodName)
{
//alert("_callFlashMethod called");
    var swf = _getFlash("tkc_chat_client");
    if (!swf)
    {
        //alert("flash object with id *tkc_chat_client* not found");
        return;
    }
    swf.SetVariable("/_root/externalMethodCaller:callMethod", methodName);
} 

function _externalMethod_chatLogout()
{
//alert("externalMethod_chatLogout called");
    _callFlashMethod("socketLogout"); 
    return false;
}

window.onunload = function()
{
    if (in_array(getVar("ctrl"), ["freechat", "hardcorechat", "fpchat", "hcChat", "login_fpchat", "login_hcChat"])) {
        _externalMethod_chatLogout();
    }
    if (in_array(getVar("ctrl"), ["freechat", "hardcorechat", "hcChat"])) {
        $.ajax({
            type: "GET",
            url: 'index.php?ctrl=chat&exitid='+exitID,
            processData: false
        });
        
    }
}
