var ptWidgetType = "";
var ptWindowType = "";
var orgNameG = PersonalTube_Organization_Name;
var orgIdG = PersonalTube_Organization_ID;
var urlG = escape(window.location.href);
var feedIdG = PersonalTube_Feed_ID;
var ptLive = "no";
if(typeof(PersonalTube_Dashboard_Widget) == "undefined" || PersonalTube_Dashboard_Widget == "")
    ptLive = "yes";
var paramsG = "live="+ptLive+"&orgId="+orgIdG+"&feedId="+feedIdG+"&org="+orgNameG+"&orgUrl="+urlG+"&source=client";
var ptJsonData, ptTimeInterval, varTimeOut, varTimeOutFlag;

/**************************UTILS*********************/
function JSONscriptRequest(fullUrl){
    this.fullUrl=fullUrl;this.noCacheIE='&noCacheIE='+(new Date()).getTime();this.headLoc=document.getElementsByTagName("head").item(0);this.scriptId='JscriptId'+JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter=1;JSONscriptRequest.prototype.buildScriptTag=function(){
    this.scriptObj=document.createElement("script");this.scriptObj.setAttribute("type","text/javascript");this.scriptObj.setAttribute("charset","utf-8");this.scriptObj.setAttribute("src",this.fullUrl+this.noCacheIE);this.scriptObj.setAttribute("id",this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag=function(){
    this.headLoc.removeChild(this.scriptObj);
}

var ie_json_ajax = false;
var other_json_ajax = false;
JSONscriptRequest.prototype.addScriptTag=function(){
    this.scriptObj.onreadystatechange= function () {
        if (this.readyState == 'complete') ie_json_ajax = true;
    }
    this.headLoc.appendChild(this.scriptObj);
}
function ptPauseRoutine(num)
{
    var date = new Date();
    var curDate = null;
    do {
        curDate = new Date();
    }
    while(curDate-date < num);
}
/****************************************************/
/*************************************************/
var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    },
    {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    },
    /*{
        prop: window.opera,
        identity: "Opera"
    },*/
    {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    },
    {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    },
    {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    },
    {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    },
    {		// for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    },
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    },
    {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    },
    { 		// for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }
    ],
    dataOS : [
    {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    },
    {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    },
    {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
    },
    {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }
    ]
};

function getAllData(jsonData)
{
    var date = new Date();
    if(varTimeOutFlag == 0)
    {
        ptJsonData = jsonData;
        ptWindowType = ptJsonData.windowType;
        
        if(typeof(PersonalTube_Dashboard_Widget) == "undefined" || PersonalTube_Dashboard_Widget == "")
          ptWidgetType = ptJsonData.widgetType;
        else
          {
              ptWidgetType = PersonalTube_Dashboard_Widget;
              //alert(ptJsonData.displayName+ "\n"+ptJsonData.titleBarBackgroundColor);
          }
          if(typeof(PersonalTube_Dashboard_Widget) != "undefined")
          ptJsonData = setPtJsonData(ptJsonData);

        initPersonalTube(ptWidgetType,ptWindowType);
    }
}

function initPersonalTube(widgetType,windowType)
{
    var jsPath = "";
    var cssPath = "";
    if(typeof(widgetType) != "undefined")
    {
        cssPath = PersonalTube_AppServerPath+"/style/personaltubeStyles.css";
        addStyleSheet(cssPath);
        if(widgetType == "standard")
        {
            jsPath = PersonalTube_AppServerPath+"/script/widgetType/standard/personaltube.js";
            addScript(jsPath);
        }
        else if(widgetType == "embed")
        {
            jsPath = PersonalTube_AppServerPath+"/script/widgetType/embed/personaltube.js";
            addScript(jsPath);
        }
        else{
            attachContentFlow();
        }
    }
    if(windowType == "iPopup")
    {
        cssPath = PersonalTube_AppServerPath+"/script/popup/csspopup.css";
        addStyleSheet(cssPath);
        var js1 = PersonalTube_AppServerPath+"/script/popup/csspopup.js";
        addScript(js1);
    }
}

function attachContentFlow()
{
    if (typeof ContentFlow === "undefined") // typeof ContentFlow === "undefined"
    {
        setTimeout(attachContentFlow, 100);
        return;
    } else {
        fnCarousel();
    }
}

function  addScript(path) {
    if (browserGlobal == "Explorer" || browserGlobal == "Konqueror" || browserGlobal == "Chrome" || browserGlobal == "Safari") {  //browser == "Explorer" ||
        document.write('<script type="text/javascript" src="'+path+'"><\/script>');
    }
    else {
        if(browserVersion == 3.6 && browserGlobal == "Firefox")
            document.write('<script type="text/javascript" src="'+path+'"><\/script>');
        else
        {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = path;
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    }
}

function addStyleSheet(path) {
    if (browserGlobal == "Firefox" || browserGlobal == "Mozilla") {// || browserGlobal == "Explorer"  || browserGlobal == "Chrome"
        var link = document.createElement('link');
        link.setAttribute('rel', 'stylesheet');
        link.setAttribute('href', path);
        link.setAttribute('type', 'text/css');
        link.setAttribute('media', 'screen');
        document.getElementsByTagName('head')[0].appendChild(link);
    }
    else {
        document.write('<link rel="stylesheet" href="'+path+'" type="text/css" media="screen" />');
    }
}

function displayNewVideo(itemId, widgetName, relatedVideos, template)
{
    itemId = escape(itemId);
    var href=PersonalTube_AppServerPath+"/GetItemMethod?itemId="+itemId+"&orgId="+orgIdG+"&feedId="+feedIdG+"&turn="+1+"&widgetTitle="+widgetName+"&relatedVideosDisplay="+relatedVideos+"&stopWords=yes&live=yes";

    if(ptWindowType == "iPopup")
    {
        //for popup playback page
        var div3 = document.createElement('div');
        div3.id = 'ptClose';
        div3.style.display = 'none';
        if (document.body.firstChild)
            document.body.insertBefore(div3, document.body.firstChild);
        else
            document.body.appendChild(div2);

        var div2 = document.createElement('div');
        div2.id = 'ptPopUpDiv';
        div2.style.display = 'none';
        if (document.body.firstChild)
            document.body.insertBefore(div2, document.body.firstChild);
        else
            document.body.appendChild(div2);

        var div1 = document.createElement('div');
        div1.id = 'ptBlanket';
        div1.style.display = 'none';
        if (document.body.firstChild)
            document.body.insertBefore(div1, document.body.firstChild);
        else
            document.body.appendChild(div1);
        if(template == "template9")
        {
            $("#ptPopUpDiv").css("width","800px");
            $("#ptPopUpDiv").css("height","550px");
        }
        else if(template == "template10")
        {
            $("#ptPopUpDiv").css("width","920px");
            $("#ptPopUpDiv").css("height","500px");
        }
        else
        {
            $("#ptPopUpDiv").css("width","920px");
            $("#ptPopUpDiv").css("height","550px");
        }

        $("#ptBlanket").attr("onClick","popup('ptPopUpDiv')");
        //END of popup playback page
        var html = "<iframe src='"+href+"' frameborder='no' scrollable='no' height='100%' width='100%' scrolling='no'></iframe>";
        $("#ptPopUpDiv").html(html);
        popup('ptPopUpDiv');
    }
    else
    {
        var mainDivID = "#PTubeWidget";
        if(ptWidgetType == "carousel")
            mainDivID = "#custSlideShow";
        
        var topBot_leftProp = 0;

        if(ptJsonData.videoListingBoxBorder == "true")
            topBot_leftProp = 1;
        var a= $(mainDivID).position().left+topBot_leftProp;
        var top1 = $(mainDivID).position().top;
        $("#ptLoader, #ptDefault").css("top",top1+(ptJsonData.videoListingBoxHeight/2-45)+"px");
        $("#ptLoader, #ptDefault").css("left",a+(ptJsonData.videoListingBoxWidth/2-30)+"px");

        $("#ptLoaderContainer").css("top",top1+"px");
        $("#ptLoaderContainer").css("left",a+"px");
        $("#ptLoaderContainer").css("width",ptJsonData.videoListingBoxWidth+"px");
        $("#ptLoaderContainer").css("height",(ptJsonData.videoListingBoxHeight-33)+"px");

        $("#ptLoaderContainer").css("display","block");
        $("#ptLoader").css("display","block");
        ptTimeInterval = setInterval("ptHideLoadImage()", 15000);
        window.open(href,"_parent","toolbar=1,width=1150px,height=600px,scrollbars=1");
    }
}

function displayEmbedVideo(thisPtObj, itemIndex)
{
    $(".thumbBg").css("background-color","transparent");
    var bkRefColor = invertHexColor('#'+ptJsonData.backgroundColor,"activeThumb");
    thisPtObj.style.backgroundColor=bkRefColor; //'#ffffff';
    
    $(".thumbBg").css("color",invertHexColor('#'+ptJsonData.backgroundColor, "inactiveThumb"));
    thisPtObj.style.color=invertHexColor(bkRefColor, "noGradient");//'#000000';
    var xLength = parseInt(ptJsonData.response.feed.feedItemList.itemCount);
    var x = ptJsonData.response.feed.feedItemList.item;
    
    if(xLength != 0)
    {
        if(itemIndex<xLength){
            var y;
            if(xLength == 1)
                y = x;
            else
                y = x[itemIndex];
            var videoAlphaCnt = Math.floor(videoEmbedWidth * 0.17);
            var returnDate = returnPtDate(y);
            $('#ptEmbedVideoTitle').html(ptTitleTruncate(escape(y.video.title), videoAlphaCnt)).attr("title",y.video.title);
            $('#ptEmbedVideoDetails div').eq(1).html(returnDate);
            $('#ptEmbedVideoDetails div').eq(3).html(y.video.viewCount);
            $('#ptEmbedVideoDetails').attr("title","Date: "+returnDate+"     Views: "+y.video.viewCount);
            $('#txtarea').val(y.video.embedTag);
            fillPTEmbedDiv();// in the 'script/widgetType/embed/personaltube.js file'
        }
    }    
}

function ptHideLoadImage()
{
    $("#ptLoaderContainer, #ptLoader").css("display","none");
    clearInterval(ptTimeInterval);
}

BrowserDetect.init();
var browserGlobal = BrowserDetect.browser;
var browserVersion = BrowserDetect.version;
var browserOS = BrowserDetect.OS;
/*************************************************/
/******Code for implementing a time out of 60 secs when there is no response from the remote server.*******/
function setPtTimeOut()
{
    varTimeOutFlag = 0;
    varTimeOut = setTimeout("ptAjaxTimeOut();", 60000);
}

function ptTrimmedValue(value)
{
    return value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function ptTitleTruncate(title, iLength){
    var newStr = "";
    title = unescape(title);
    if(title == null)
        title = "";
    newStr = ptTrimmedValue(title);
    if( newStr.length > iLength)
    {
        var li = newStr.lastIndexOf(" ");
        if(li > iLength-3)
        {
            newStr = newStr.substring(0, li);
            newStr = ptAppendDots(ptTitleTruncate(newStr, iLength), 0 , iLength);
        }
        else
        {
            if(li == -1)
            {
                if(newStr.length > iLength)
                    newStr = ptAppendDots(newStr, 0, iLength-3, "no");
            }
            else
                newStr = ptAppendDots(newStr, 0, li);
        }
    }
    return newStr;
}

function ptAppendDots(str , init, last, eliminate)
{
    var returnStr = str
    var partStr = str.substring(str.length-3, str.length);
    if(str.substring(str.length-3, str.length) != "..."){
        if(eliminate == "no")
            returnStr = str.substring(init, last) + "...";
        else
        {
            returnStr = str.substring(init, str.lastIndexOf(" ")) + "..." ;
            if(returnStr == "...")
                returnStr = str.substring(init, str.indexOf(partStr)) + "..." ;
        }
    //   returnStr = str.substring(init, str.lastIndexOf(" ")) + "..." ;
    }
    return returnStr;
}

function ptAjaxTimeOut()
{
    varTimeOutFlag = 1;
    clearTimeout(varTimeOut);
}
/******END OF - Code for implementing a time out of 60 secs when there is no response from the remote server.*******/
//Get windowType and widget info using JSR method
var req1 = "";
if(typeof(PersonalTube_Dashboard_Widget) == "undefined" || PersonalTube_Dashboard_Widget == "")
{
    req1  = PersonalTube_AppServerPath+"/JSRGetFeed?callback=getAllData&data="+encodeURIComponent(paramsG)+"&_="+Math.random();
}
else
{
    req1  = PersonalTube_AppServerPath+"/JSRGetFeed?callback=getAllData&widgetType="+PersonalTube_Dashboard_Widget+"&data="+encodeURIComponent(paramsG)+"&_="+Math.random();
}
    other_json_ajax = true;
    setPtTimeOut();
    addScript(req1);

function RGBColor(color_string)
{
    this.ok = false;

    // strip any leading #
    if (color_string.charAt(0) == '#') { // remove # if any
        color_string = color_string.substr(1,6);
    }

    color_string = color_string.replace(/ /g,'');
    color_string = color_string.toLowerCase();

    // array of color definition objects
    var color_defs = [
    {
        re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
        example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
        process: function (bits){
            return [
            parseInt(bits[1]),
            parseInt(bits[2]),
            parseInt(bits[3])
            ];
        }
    },
    {
        re: /^(\w{2})(\w{2})(\w{2})$/,
        example: ['#00ff00', '336699'],
        process: function (bits){
            return [
            parseInt(bits[1], 16),
            parseInt(bits[2], 16),
            parseInt(bits[3], 16)
            ];
        }
    },
    {
        re: /^(\w{1})(\w{1})(\w{1})$/,
        example: ['#fb0', 'f0f'],
        process: function (bits){
            return [
            parseInt(bits[1] + bits[1], 16),
            parseInt(bits[2] + bits[2], 16),
            parseInt(bits[3] + bits[3], 16)
            ];
        }
    }
    ];

    // search through the definitions to find a match
    for (var i = 0; i < color_defs.length; i++) {
        var re = color_defs[i].re;
        var processor = color_defs[i].process;
        var bits = re.exec(color_string);
        if (bits) {
            channels = processor(bits);
            this.r = channels[0];
            this.g = channels[1];
            this.b = channels[2];
            this.ok = true;
        }
    }

    // validate/cleanup values
    this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
    this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
    this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);

    // some getters
    this.toRGB = function () {
        return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
    }
    this.toHex = function () {
        var r = this.r.toString(16);
        var g = this.g.toString(16);
        var b = this.b.toString(16);
        if (r.length == 1) r = '0' + r;
        if (g.length == 1) g = '0' + g;
        if (b.length == 1) b = '0' + b;
        return '#' + r + g + b;
    }
}

function invertHexColor(refColor, type)
{

    var tColor = new RGBColor('#ffffff'), textColor;
    var color = new RGBColor(refColor);
    /*//Pure invert
     if (color.ok) {
        if (color.r < 0x20 && color.g < 0x20 && color.b < 0x20)
        {
            tColor.r = color.r + 0x20;
            tColor.g = color.g + 0x20;
            tColor.b = color.b + 0x20;
        }
        else
        {
            tColor.r = color.r + ((color.r < 32) ? 0x10 : -0x10); //128 instead of 32
            tColor.g = color.g + ((color.g < 32) ? 0x10 : -0x10);
            tColor.b = color.b + ((color.b < 32) ? 0x10 : -0x10);
        }
    }*/

//black or white text color depending on the background.
    if (color.ok) {
        //Since the widget background looks to be faded to a lighter shade in the video list,
        //we add 0x88 to the actual color.
        if((typeof(type) != "undefined" || type != "") && type == "inactiveThumb")
        {
            color.r += 0x88; color.g += 0x88; color.b += 0x88;
            if(color.r > 0xff)
                color.r = 0xff;
            if(color.g > 0xff)
                color.g = 0xff;
            if(color.b > 0xff)
                color.b = 0xff;
        }
        
                        if (color.r <= 0x88 && color.g <= 0x88 && color.b <= 0x88)
                        {
                            if((typeof(type) != "undefined" || type != "") && type == "activeThumb")
                            {
                                tColor.r = color.r + 0xff;
                                tColor.g = color.g + 0xff;
                                tColor.b = color.b + 0xff;
                            }
                            else
                            {
                                tColor.r = 0xff;
                                tColor.g = 0xff;
                                tColor.b = 0xff;
                            }
                        }
                        else
                        {
                            if((typeof(type) != "undefined" || type != "") && type == "activeThumb")
                            {
                              //  alert("color.r: "+color.r+", color.g: "+color.g+", color.b: "+color.b);
                                tColor.r = color.r + ((color.r > 128) ? -156 : 156); //128 instead of 32
                                tColor.g = color.g + ((color.g > 128) ? -156 : 156);
                                tColor.b = color.b + ((color.b > 128) ? -156 : 156);
                              //  alert("tColor.r: "+tColor.r+", tColor.g: "+tColor.g+", tColor.b: "+tColor.b);
                            }
                            else
                            {
                                tColor.r = 0x00; //128 instead of 32
                                tColor.g = 0x00;
                                tColor.b = 0x00;
                            }
                        }
    }
        if(tColor.r > 0xff)
            tColor.r = 0xff;
        if(tColor.g > 0xff)
            tColor.g = 0xff;
        if(tColor.b > 0xff)
            tColor.b = 0xff;

        if(tColor.r < 0x00)
            tColor.r = 0x10;
        if(tColor.g < 0x00)
            tColor.g = 0x10;
        if(tColor.b < 0x00)
            tColor.b = 0x10;

    if (tColor.ok) { // 'ok' is true when the parsing was a success
        /* alert("RGB: "+tColor.r + ', ' + tColor.g + ', ' + tColor.b+"\n"+
                                            "HEX:"+tColor.toHex()+"\n"+
                                            "RGB:"+tColor.toRGB());*/
        textColor = tColor.toHex();
    }
    return textColor;
}
