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 paramsG = "live=yes&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;
        ptWidgetType = jsonData.widgetType;
        ptWindowType = jsonData.windowType;
        initPersonalTube(ptWidgetType,ptWindowType);
    }
else
        {return;}
}

function initPersonalTube(widgetType,windowType)
{
    var jsPath = "";
    var cssPath = "";
    if(widgetType == "standard" || widgetType == "carousel")
    {
        cssPath = PersonalTube_AppServerPath+"/style/personaltubeStyles.css";
        addStyleSheet(cssPath);
        if(widgetType == "standard")
        {
            jsPath = PersonalTube_AppServerPath+"/script/widgetType/standard/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 == "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 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 = "";
        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
        if(str.substring(str.length-3, str.length) != "..."){
            if(eliminate == "no")
               returnStr = str.substring(init, last) + "...";
            else
               returnStr = str.substring(init, str.lastIndexOf(" ")) + "..." ;
        }
        return returnStr;
    }

function ptAjaxTimeOut()
{
    varTimeOutFlag = 1;
getAllData();
    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  = PersonalTube_AppServerPath+"/JSRGetFeed?callback=getAllData&data="+encodeURIComponent(paramsG)+"&_="+Math.random();
other_json_ajax = true;
setPtTimeOut();
addScript(req1);
