var thickboxIframeDownload = "&TB_iframe=true&height=303&width=470&modal=true";

/**
 * Ajax call to URL and update content of div
 *
 * @param url
 * @param div
 * @return
 */
function getRequest(url, div) {
    $.get(url, function(data) {
        document.getElementById(div).innerHTML = data;
        // $('#' + div).innerHTML = data;
        });
}

function postRequest(url, div) {
    $.post(url, function(data) {
        document.getElementById(div).innerHTML = data;
    });
}

function getRequestWithScript(url, div) {
    $.ajax( {
        type :"GET",
        url :url,
        success : function(data) {
            document.getElementById(div).innerHTML = data;
            evalJScript(data);
        }
    });
}

function postRequestWithScript(url, div) {
    $.ajax( {
        type :"POST",
        url :url,
        success : function(data) {
            document.getElementById(div).innerHTML = data;
            evalJScript(data);
        }
    });
}

function evalJScript(data) {
    var scripts = getJavaScript(data);
    // alert(scripts);
    return evalJavaScript(scripts);
}

function getJavaScript(data) {
    var script, scripts;
    scripts = [];
    var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
    while ((script = regexp.exec(data))) {
        scripts.push(script[1]);
    }
    return scripts;
}

function getAlertJavaScript(scripts) {
    var alerts = [];
    for (i = 0; i < scripts.length; i++) {
        if (scripts[i].indexOf('alert') != -1) {
            alerts.push(scripts[i]);
        }
    }
    return alerts;
}

function evalJavaScript(scripts) {
    scripts = scripts.join('\n');
    // alert(scripts);
    if (scripts)
        (window.execScript) ? window.execScript(scripts) : window.setTimeout(
                scripts, 0);
    return true;
}

function logout(logoutUrl) {
    var expireCookie = "STO_user_id=;expires=" + (new Date(1)).toGMTString()
            + "; path=/; domain=ufinity.com;";
    document.cookie = expireCookie;
    var expireCookie = "HTTP_email=;expires=" + (new Date(1)).toGMTString()
            + "; path=/; domain=ufinity.com;";
    document.cookie = expireCookie;
    var expireCookie = "HTTP_user_id=;expires=" + (new Date(1)).toGMTString()
            + "; path=/; domain=ufinity.com;";
    document.cookie = expireCookie;
    makeFormByUrl(logoutUrl);
}

function openNewWindow(pageUrl, title, width, height) {
    var left = (screen.width/2)-(width/2);
    var top = (screen.height/2)-(height/2);
    window.open(pageUrl, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+width+', height='+height+', top='+top+', left='+left+'');
}

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_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_findObj(n, d) { // v4.01
    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 && d.getElementById)
        x = d.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 postCommentsOfArticleTimeout(){
    setTimeout(postCommentsOfArticle, 50);
}

        
function checkForMaxCharactersInCommentBox(form, maxchars){
  	if(form.text.value.length > maxchars) {
		alert('Please limit your comment to ' + maxchars + ' characters');
		return false; 
	}
	else{ 
		return true; 
	}
}

function validatePostComment(loginTextElement, isLogin, userName, commentArea) {
    if (isLogin != "true" || userName == null || userName == "" || typeof(userName) == 'undefined' ||  userName.length == 0) {
        alert("Please login to comment.");
        if (loginTextElement != null) {
            loginTextElement.focus();
        }
        return false;
    }

    var content = $.trim(commentArea.value);
    if (typeof(content) == 'undefined' || content == '') {
        alert("Please enter your comment");
        commentArea.focus();
        return false;
    }

    if (content.length < 10) {
        alert("Please lengthen your message to at least 10 characters.");
        commentArea.focus();
        return false;
    }

    if (content.length > 1000) {
        alert("Please lengthen your message to less than 1000 characters.");
        commentArea.focus();
        return false;
    }

    if (!checkValid(content)){
        alert("Not script in the comment!");
        commentArea.focus();
        return false;
    }

    return true;
}

function checkValid(content){
    var filterExpr = ".*<[^<>]+>.*";
    if (content.match(filterExpr) != null){
        return false;
    }
    return true;
}

function changeIcon(e, type) {
    var title = $(e.target).attr("name");
    if (title == null || title.indexOf("_icon") < 0) {
        title = $(e.target).parent(".iconlink").attr("name");
    }
    var iconName = title;
    var mouseOverIconName = iconName + "_mouseover";
    var mouseOutIconName = iconName + "_mouseout";
    var toRemoveClass;
    var toAddClass;

    if (type == "mouseover") {
        toRemoveClass = mouseOutIconName;
        toAddClass = mouseOverIconName;
    } else if (type == "mouseout") {
        toRemoveClass = mouseOverIconName;
        toAddClass = mouseOutIconName;
    } else
        return;

    if ($(e.target).hasClass(iconName)) {
        $(e.target).removeClass(toRemoveClass);
        $(e.target).addClass(toAddClass);
    } else {
        $(e.target).children("." + iconName).removeClass(toRemoveClass);
        $(e.target).children("." + iconName).addClass(toAddClass);
    }
}

function trim(stringToTrim) {
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function makeFormByUrl(actionUrl) {
    if (typeof (actionUrl) == 'undefined') {
        return;
    }
    var decodedUrl = unescape(actionUrl);
    var formJq = $("<form></form>");
    var addrPos = decodedUrl.indexOf("?");
    var sectionPos = decodedUrl.indexOf("#");
    var url = "";
    var section = "";
    var parameters = "";

    if (sectionPos != -1) {
        if (addrPos != -1) {
            url = decodedUrl.substring(0, addrPos);
            parameters = decodedUrl.substring(addrPos + 1, sectionPos);
            section = decodedUrl.substring(sectionPos + 1);
        } else {
            url = decodedUrl.substring(0, sectionPos);
            section = decodedUrl.substring(sectionPos + 1);
        }
    } else {
        if (addrPos != -1) {
            url = decodedUrl.substring(0, addrPos);
            parameters = decodedUrl.substring(addrPos + 1);
        } else {
            url = decodedUrl;
        }
    }

    var urlWithSection = "";
    if(section != ""){
        urlWithSection = url + "#" + section;
    }
    else{
        urlWithSection = url;
    }

    var params;
    if (typeof (parameters) != 'undefined') {
        params = parameters.split("&");
    }

    formJq.attr( {
        method : 'post',
        action : urlWithSection
    });

    if (typeof (params) != 'undefined') {
        for ( var i = 0, len = params.length; i < len; i++) {
            var name_value = params[i].split("=");
            if (name_value.length == 2) {
                var hidden = $("<input type='hidden' name='" + name_value[0] + "'>");
                hidden.attr("value", name_value[1]);
                formJq.append(hidden);
            }
        }
    }

    formJq.appendTo("body");
    formJq.css('display', 'none');
    formJq.submit();

    return false;
}
function callNR() {
    var strHref = window.location.href;
    var url;
    if ( strHref.indexOf("?") > -1 ){
        url = strHref.substr(0, strHref.indexOf("?")).toLowerCase();
    }
    else url = strHref;
    if(self._rsEvent && self._rsCG) {
        _rsEvent(url, _rsCG);
    }
}

function playVideoWithFullArguments(swfObjectPath, playBarUrl, playerWidth, playerHeight, videoDivId, videoFilePath, netratingUrl, netratingSite, browserUrl) {
    videoFilePath = trim(videoFilePath);
    var objId = 'mediaplayer';
    var s1 = new SWFObject(swfObjectPath, objId, playerWidth, playerHeight, "8", "#000000");
    s1.addParam("allowfullscreen", "true");
    s1.addParam("allowscriptaccess", "always");
    // wmode will crash ff2
    if ($.browser.msie || $.browser.safari) {
        s1.addParam("wmode", "transparent");
    }
    s1.addVariable("playbarurl", playBarUrl);
    s1.addVariable("siteinfo", "false");
    s1.addVariable("enablejs", "true");
    s1.addVariable("javascriptid", objId);
    s1.addVariable("width", playerWidth);
    s1.addVariable("height", playerHeight);
    s1.addVariable("debug", "false");
    s1.addVariable("showdigits", "total");
    s1.addVariable("playmode", "vod");
    s1.addVariable("volume", "0.5");
    s1.addVariable("buffer", "2");
    s1.addVariable("file", videoFilePath);
    s1.addVariable("repeat", "false");
    s1.addVariable("vodnav", "false");
    s1.addVariable("autostart", "true");
    s1.addVariable("warn_delay", "1800");
    s1.addVariable("warn_timeout", "120");
    s1.addVariable("toptitle", "");
    s1.addVariable("nrurl", escape(netratingUrl));
    s1.addVariable("nrsi", escape(netratingSite));
    s1.addVariable("nrrp", escape(browserUrl));
    s1.write(videoDivId);
}

function playVideo(contextPath, videoFilePath, netratingUrl, netratingSite) {
    videoFilePath = trim(videoFilePath);
    var swfObjectPath = contextPath + "/flashplayer/razortv.swf";
    var playBarUrl = contextPath + "/images/redpanel.png";
    var playerWidth = "500";
    var playerHeight = "355";
    var videoDivId = "playerContainer";
    var browserUrl = document.location.href;
    var jsessionIndex = browserUrl.indexOf(";jsessionid=");
    if (jsessionIndex > 0){
        browserUrl = browserUrl.substring(0, jsessionIndex);
    }

    playVideoWithFullArguments(swfObjectPath, playBarUrl, playerWidth, playerHeight, videoDivId, videoFilePath, netratingUrl, netratingSite, browserUrl);
}

function updateShareContent(contextPath, videoFilePath, netratingUrl, netratingSite, pathToHost, videoUrl ){
    videoFilePath = trim(videoFilePath);
    // update share content
    var completeVideoUrl = pathToHost + videoUrl;
    $("#videoUrl").val(completeVideoUrl);

    var swfObjectPath = contextPath + "/flashplayer/razortv.swf";
    var playBarUrl = contextPath + "/images/redpanel.png";
    var completeSwfFilePath ="";
    //check if the link starting with http
    var subSection = swfObjectPath.substring(4,0);
    if (subSection == "http"){
        completeSwfFilePath = swfObjectPath;
    }
    else{
        completeSwfFilePath = pathToHost + swfObjectPath;
    }

    //check if the link starting with http
    subSection = playBarUrl.substring(4,0);
    if (subSection == "http"){
        completePlaybarFilePath = playBarUrl;
    }
    else{
        completePlaybarFilePath = pathToHost + playBarUrl;
    }

    var playerWidth = "500";
    var playerHeight = "355";
    var browserUrl = document.location.href;
    var jsessionIndex = browserUrl.indexOf(";jsessionid=");
    if (jsessionIndex > 0){
        browserUrl = browserUrl.substring(0, jsessionIndex);
    }

    var embedText = "<object><param name='movie' value='" + completeSwfFilePath + "'></param>"
        + "<param name='wmode' value='transparent'></param><embed src='"
        + completeSwfFilePath + "' type='application/x-shockwave-flash' allowfullscreen='true' "
        + "width='" + playerWidth + "' height='" + playerHeight + "' flashvars='@vars@'></embed></object>";
    var flashVars = "file=" + escape(videoFilePath)
        + "&vodnav=false&siteinfo=false&autostart=false"
        + "&playbarurl=" + completePlaybarFilePath
        + "&nrurl=" + escape(netratingUrl)
        + "&nrsi=" + escape(netratingSite)
        + "&nrrp=" + escape(browserUrl);

    var newEmbedText = embedText.replace(/@vars@/g, flashVars);
    $("#embedCode").val(newEmbedText);
}

function playVideoAndUpdateShareContent(contextPath, videoFilePath, netratingUrl, netratingSite, pathToHost, videoUrl) {
    var swfObjectPath = contextPath + "/flashplayer/razortv.swf";
    var playBarUrl = contextPath + "/images/redpanel.png";
    var playerWidth = "500";
    var playerHeight = "355";
    var videoDivId = "playerContainer";
    var videoFilePath = trim(videoFilePath);

    updateShareContent(contextPath, videoFilePath, netratingUrl, netratingSite, pathToHost, videoUrl);
    var browserUrl = document.location.href;
    var jsessionIndex = browserUrl.indexOf(";jsessionid=");
    if (jsessionIndex > 0){
        browserUrl = browserUrl.substring(0, jsessionIndex);
    }
    playVideoWithFullArguments(swfObjectPath, playBarUrl, playerWidth, playerHeight, videoDivId, videoFilePath, netratingUrl, netratingSite, browserUrl);
}

