// JavaScript Document

/* global varriables to play with video and audio palyer switching	*/
var videoPlaying = false;
var audioPlay = false;
var myPlayList;
var aspList;
var player; //jwplayer
var playItem = 0;
var jpPlayTime;
var jpTotalTime;
var song;
var pl_modified = false;
//functions
var countFunc;
var fancyFunc;
var termsFunc;
var PlayListActionsUI;


// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};




jQuery(function($) {
    createCookie("test", "a", 5);
    //alert($.isPlainObject("swfobject"));
    var uid = readCookie("userid_");
    if (uid != 0) //chagne the > condition into !=
    {
        LoggedIn();
        //PlayListActionsUI(true);
    }
    else {
        LoggOut();
        //PlayListActionsUI(false);
    }


    /* Jplayer Call
    ===========================================================*/
    //var playItem = 0;



    // Local copy of jQuery selectors, for performance.
    jpPlayTime = $("#jplayer_play_time");
    jpTotalTime = $("#jplayer_total_time");

    /*  Jplayer Player Events Should stay in jquery scope
    ---------------------------------------------------------------------------*/
    $("#jplayer_previous").click(function() {
        playListPrev();
        $(this).blur();
        return false;
    });

    $("#jplayer_next").click(function() {
        playListNext();
        $(this).blur();
        return false;
    });

    /* Playlist Toggling when mange playlist btn hit */
    $(".plBtn").click(function() {
        var $this = $(this);
        var toggle = $this.hasClass("plBtnActive");
        if (toggle == true) {
            //hide it
            //$("div.jp-playlist").stop().animate({ bottom: '-300px' },500);
            $("div.jp-playlist").css({ bottom: '-300px' });
            $this.removeClass("plBtnActive");
        }
        else {
            //show it
            //$("div.jp-playlist").stop().animate({ bottom: '80px' },500);
            $("div.jp-playlist").css({ bottom: '80px' });
            $this.addClass("plBtnActive");
        }
        return false;
    });

    /*  Jplayer Delegates and handlers
    ---------------------------------------------------------------------------*/
    $("body").delegate(".addtoplaylist", "click", function() {
        //ad1d songs to audio playlist
        var $elePL = $(".jp-playlist");
        var isAdd = false;
        var $this = $(this);
        song = {
            SongId: $this.attr("songid"),
            SongTitle: $this.attr("songtitle"),
            mp3: $this.attr("mp3"),
            MediaTypeId: 2
        };

        if (myPlayList.length < 31) //max songs check
        {
            for (i = 0; i < myPlayList.length; i++) {
                if (song.SongId == myPlayList[i].SongId) {
                    //do nothing
                    isAdd = true;
                    break;
                }
                else {
                }
            }

            if (isAdd != true) {
                //add song into playlist
                myPlayList.splice(0, 0, song);
                displayPlayList();
                $("#jplayer_playlist ul li").eq(playItem + 1).addClass("jplayer_playlist_current").find("a:first").addClass("jplayer_playlist_current");
                playItem = playItem + 1;
                createCookie("myPlayList", JSON.stringify(myPlayList), 5);
                $elePL.css("bottom", "80px");
                $(".jp-message").html("<p>Song added into the playlist.</p>").show().animate({ width: '234px' }, 3000, function() {
                    $(this).fadeOut();
                });
                pl_modified = true;
            }
            else {
                //already exist into playlist
                $elePL.css("bottom", "80px");
                $(".jp-message").html("<p>Song already exist into the playlist.</p>").show().animate({ width: '234px' }, 3000, function() {
                    $(this).fadeOut();
                });
            }
        }
        else {
            $elePL.css("bottom", "80px");
            $(".jp-message").html("<p>Playlist can only contains 30 songs.</p>").show().animate({ width: '234px' }, 3000, function() {
                $(this).fadeOut();
            });
        }
        return false;
    });

    /* Remove From playlist 
    ============================================================*/
    $("body").delegate(".remove", "click", function() {
        var $this = $(this);
        var $liEle = $this.closest("li");
        var indexx = $("#jplayer_playlist ul li").index($liEle);
        //console.log("index=" + indexx + ",playitem=" + playItem);

        myPlayList.remove(indexx);

        if (indexx < playItem) {
            playItem = playItem - 1;
        }
        else if (playItem == indexx && myPlayList.length > 0) {

            $("#jplqyer_song_title").html("");
            $("#jquery_jplayer").jPlayer("clearFile");
            if (myPlayList.length > playItem) //their are songs after the deleted songs
            {
                $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3);
                $("#jplqyer_song_title").html(myPlayList[playItem].SongTitle);
            }
            else {
                //deleted song was the last song in playlist - so choose first song
                playItem = 0;
                $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3);
                $("#jplqyer_song_title").html(myPlayList[playItem].SongTitle);
            }
        }
        else {
            $("#jplqyer_song_title").html("");
            $("#jquery_jplayer").jPlayer("clearFile");
        }

        displayPlayList();

        $("#jplayer_playlist ul li").eq(playItem).addClass("jplayer_playlist_current").find("a:first").addClass("jplayer_playlist_current");
        //$("#jplayer_playlist ul li").eq(playItem).addClass("jplayer_playlist_current").find("a");
        createCookie("myPlayList", JSON.stringify(myPlayList), 5);
        pl_modified = true;
        //save myplaylist into cookies
        return false;
    });

    $(".pl-reset").click(function() {
        GetPlayList(); //getplaylist via ajax
        return false;
    });

    $(".pl-clear").click(function() {
        myPlayList.remove(0, myPlayList.length);
        displayPlayList();
        createCookie("myPlayList", JSON.stringify(myPlayList), 5);
        return false;
    });

    $("body").delegate(".pl-UpdateDB", "click", function() {
        var uid = readCookie("userid_");
        var $elePL = $(".jp-playlist");
        $elePL.css("bottom", "80px");
        if (uid != 0) {
            if (myPlayList.length > 0) //empty playlist check
            {
                $(".jp-message").html("<p>Saving your playlist ...</p>").show().animate({ width: '234px' }, 3000, function() {
                    $(this).fadeOut();
                });
                SavePlayList();

            }
            else {
                $(".jp-message").html("<p>Can't save empty playlist ...</p>").show().animate({ width: '234px' }, 3000, function() {
                    $(this).fadeOut();
                });
            }
        }
        else {

            $(".jp-message").html("<p>Please login to save your playlist ...</p>").show().animate({ width: '234px' }, 3000, function() {
                $(this).fadeOut();
            });
        }

        return false;
    });

    /*  Jplayer Player Delegates Ends
    ---------------------------------------------------------------------------*/

    /* countdown */
    countFunc = function countdown() {
        if ($('#countdown_dashboard').size() > 0) {
            $('#countdown_dashboard').countDown({
                targetDate: {
                    'day': 6,
                    'month': 6,
                    'year': 2010,
                    'hour': 22,
                    'min': 0,
                    'sec': 0
                }
                //oncomplete event
                //onComplete: function() { $('#complete').slideDown() }
            });
        }
    }

    /* tabs */
    if ($('#tabs').size() > 0) {
        $("#tabs").tabs();
    }

    /*
    Proxy click handlers for fancy box 
    =======================================================================================*/

    //fancy plugin wrapper
    fancyFunc = function FancyCall() {
        if ($(".picsW").size() > 0) {
            $("a[rel=picGroup]").fancybox({
                'transitionIn': 'none',
                'transitionOut': 'none',
                'titlePosition': 'over',
                'titleFormat': function(title, currentArray, currentIndex, currentOpts) {
                    return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
                }
            });
        }
    }

    termsFunc = function fancypop() {
        var download = $(this).attr("flink");
        var divele = $(this).attr("href");
        //$("#confirmdownload").attr("href", download);

        $("#dummylink").fancybox({
            'titleposition': 'inside',
            'transitionin': 'none',
            'transitionout': 'none'
        });


        $("#dummylinkLike").fancybox({
            'titleposition': 'inside',
            'transitionin': 'none',
            'transitionout': 'none'
        });
    }

    $("body").delegate(".proxydownload", "click", function() {
        var download = $(this).attr("flink");
        var divEle = $(this).attr("href");
        //alert(download);
        $("#confirmDownload").attr("href", download);
        $("#dummylink").attr("href", divEle);
        $("#dummylink").trigger("click");
        return false;
    });

    $("body").delegate(".proxyLike", "click", function() {
        //read cookie to check if user is login or not
        //show fancy box if they are not login
        //if they login make ajax call with callback function for sucess case to generate another ajax call to update current page
        var user = readCookie("userid_");
        // alert("user is = " + user);

    });




    /*  Disabled click handler
    ========================================================*/
    $("body").delegate("a.disable", "click", function() {
        // do nothing
        return false;
    });


    /* facebook gigya click handler 
    ===========================================================*/
    //    $("body").delegate(".gigya-fb", "click", function() {
    //        alert("hi");
    //        return false;
    //    });

    $(".gigya-fb").click(function() {
        alert("najam");
        gigya.services.socialize.plugins.login.providerClick('loginDiv', 'myspace');
        return false;
    });

    // updates scroll
    if ($('.scroll-updates').size() > 0) {
        $('.scroll-updates').cycle({
            cleartype: 1,
            timeout: 4000,
            speed: 900,
            fx: 'scrollDown',
            pause: 1
        });
    }


});                               //document ready ends

/* video array function */
function videoarray(videos) {
    if (videos.size() > 0) {
        
        videos.each(function(i) {
        var width = $(this).attr("width"),
        height = $(this).attr("height"),
        flv = $(this).attr("flv"),
        img = $(this).attr("img"), 
        target = $(this).attr("target");
            CreatePlayer(flv, target, img, width, height);

        });
    }
    else {
     
    }
}

/* JWPlayer Area
================================================================*/
//this function using code based on swobject 2.1
function CreatePlayer(file, target, Img, Width, Height) {
    // file = "http%3a%2f%2fccweb2.csquareonline.com%3a8080%2fcokestudio%2fStreaming.aspx%3ffileId%3d1%26typeId%3d1";
    //file = "http://www.youtube.com/watch?v=TPYdpZpDo6A";
    // alert(file);
    var flashvars = {
        file: file,
        image: Img,
        autostart: "false",
        //type: "http",
        fullscreen: "true",
        skin: "Streaming/cs.swf",
        stretching: "uniform",
        controlbar: "over"
    }
    var params = {
        allowfullscreen: "true",
        allowscriptaccess: "always",
        bgcolor: "#000000",
        wmode: "transparent"
    }
    var attributes = {
        id: "player1",
        name: "player1"
    }
   // console.log(img);
    swfobject.embedSWF("Streaming/player.swf", target, Width, Height, "9.0.115", false, flashvars, params, attributes);
}

function playerReady(thePlayer) {
    player = document.getElementById(thePlayer.id);
    addListeners();
}

function addListeners() {
    if (player) {
        player.addModelListener("STATE", "stateListener");
    } else {
        setTimeout("addListeners()", 100);
    }
}

function stateListener(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED	       
    currentState = obj.newstate;
    previousState = obj.oldstate;

    var tmp = document.getElementById("stat");
    if (tmp) {
        tmp.innerHTML = "current state: " + currentState +
		        "<br>previous state: " + previousState;
    }
    else {
        //console.log("current state: " + currentState + "<br>previous state: " + previousState);
    }

    if (currentState == "PLAYING") {
        //stop coke audio player and hide it
        $("#jquery_jplayer").jPlayer("pause");
        $(".plBtn,.jp-playlist").hide();
        $(".jp-interface").animate({ bottom: "-100px" }, 500, function() { });
        //$("#cokePlayer").css("left","-999999px");
    }


    if (currentState == "COMPLETED" || currentState == "PAUSED") {
        //document.location.href="http://www.longtailvideo.com/players/jw-flv-player/";

        $(".plBtn,.jp-playlist").show();
        $(".jp-interface").animate({ bottom: "0px" }, 500, function() { });
    }
}

// JW Video Player function
function PlaceVideo(file, target, Img, Width, Height) {
    var s1 = new SWFObject('videos/player.swf', 'player', Width, Height, '9', '#000000');
    s1.addParam('allowfullscreen', 'true');
    s1.addParam('allowscriptaccess', 'always');
    s1.addParam('wmode', 'transparent');
    s1.addParam('flashvars', 'file=' + file + '&image=' + Img + '&fullscreen=true&controlbar=bottom&skin=videos/cs.swf&stretching=uniform&controlbar=over');
    s1.write(target);
}

// flash swfobject call
function flashswf(file, target, Width, Height, ID) {
    //console.log(file+","+target+","+Img+","+Width+","+Height);
    var flashvars = {
}
var params = {
    //allowfullscreen:"true", 
    allowscriptaccess: "always",
    wmode: "transparent",
    menu: "false"
}
var attributes = {
    id: ID,
    name: ID
}
swfobject.embedSWF(file, target, Width, Height, "9.0.115", false, flashvars, params, attributes);
}

// flash button ajax
function clickflash(url) {
    var $aEle = $("#flashbutton");
    $aEle.trigger("click");
}

/*
Cookie Management
==================================================================================*/
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return 0;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

//reinitialize user info freom cokkie
function socialUserCookie() {

    UGUID = readCookie('guid_');
    UNAME = readCookie('UNAME_');
    UEMAIL = readCookie('UEMAIL_');
    CSUID = readCookie('userid_');

}

function OpenWindow(url) {

    var l = (screen.availWidth / 2) - 210;
    var t = (screen.availHeight / 2) - 160;
    var winhnd = window.open(url, 'name', 'left=' + l + ',top=' + t + ',width=600,height=520,resizable=no,status=no,toolbar=no,scroll=no, location=no');
}

function ResizeGigya() {
    var $loginDiv = $("#loginDiv");
    $loginDiv.find("img").each(function(i) {
        // var gigyaDiv = $(this).closest("#gigya").size();
        //alert(gigyaDiv);
        //if(gigyaDiv == 0)
        //{
        $(this).css({ height: "15px", width: "15px" }).closest("td").css({ height: "15px", width: "15px" }).find("div").css({ height: "15px", width: "15px" });
        //}        
    });
    $loginDiv.find("table").css({ height: "auto" });
    $loginDiv.show();
}

function ResizeGigyaImproved(element) {
    var $Div = $(element);
    $Div.find("img").each(function(i) {
        $(this).css({ height: "30px", width: "30px" }).closest("td").css({ height: "30px", width: "30px" }).find("div").css({ height: "30px", width: "30px" });
    });
    $Div.find("table").css({ height: "auto" });
    $Div.show();
}

/// Render Playlist Actions Buttons depeding upon login state
PlayListActionsUI = function(login) {
    if (login) {
        $(".jp-actions").prepend('<a href="#" class="left pl-UpdateDB">Save Playlist</a>');
    }
    else {
        $(".pl-UpdateDB", ".jp-actions").detach();
    }
}

function LoggedIn() {
    $("#LoggedIn").show();
    $("#loginDiv").hide();
    $(".login-meta").hide();

}
function LoggOut() {
    $("#LoggedIn").hide();
    $("#loginDiv").show();
    $(".login-meta").show();
}
jQuery(window).load(function() {
    //gigya image resizing
    //$("#loginDiv #loginDiv_bottomLink").detach();

    ResizeGigya();
    var uid = readCookie("userid_");
    if (uid > 0) {
        LoggedIn();
    }
    else {
        LoggOut();
    }
});

/*  Jplayer Player function Definations : should be globall
---------------------------------------------------------------------------*/
function displayPlayList() {
    $("#jplayer_playlist ul").empty();
    for (i = 0; i < myPlayList.length; i++) {
        var listItem = (i == myPlayList.length - 1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
        listItem += "<a href='#' id='jplayer_playlist_item_" + i + "' tabindex='1'>" + myPlayList[i].SongTitle + "</a><a class='remove' href='#'>x</a></li>";
        $("#jplayer_playlist ul").append(listItem);
        $("#jplayer_playlist_item_" + i).data("index", i).click(function() {
            var index = $(this).data("index");
            //alert("index = " + index + ", playitem=" + playItem);
            if (playItem != index) {
                playListChange(index);
            } else {
                $("#jquery_jplayer").jPlayer("play");
            }
            $(this).blur();
            return false;
        });
    }
    if (myPlayList.length == 0) {
        $(".jp-message").html("<p>Click on Add To PlayList button to add songs into your playlist.</p>").show();
        $("#jplqyer_song_title").html("");
        $("#jquery_jplayer").jPlayer("clearFile");
    }
    else {
        $(".jp-message").hide();
    }
}

function playListInit(autoplay) {
    if (autoplay) {
        playListChange(playItem);
    } else {
        playListConfig(playItem);
    }
}

function playListConfig(index) {
    $("#jplayer_playlist_item_" + playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
    $("#jplayer_playlist_item_" + index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
    //console.log($("#jplayer_playlist_item_"+index).text());
    $("#jplqyer_song_title").html($("#jplayer_playlist_item_" + index).text());
    //alert(index);
    playItem = index;
    $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3);
}

function playListChange(index) {
    playListConfig(index);
    $("#jquery_jplayer").jPlayer("play");
}

function playListNext() {
    var index = (playItem + 1 < myPlayList.length) ? playItem + 1 : 0;
    playListChange(index);
}

function playListPrev() {
    var index = (playItem - 1 >= 0) ? playItem - 1 : myPlayList.length - 1;
    playListChange(index);
}


function GetPlayList() {
    var undef = undefined;
    var $elePL = $(".jp-playlist");
    $elePL.css("bottom", "80px");
    $(".jp-message").html("<p>Loading ...</p>").show().animate({ width: '234px' }, 3000, function() {
        $(this).fadeOut();
    });

    //$(".jp-message").html("<p>Loading ...</p>").show();
    var loginID = readCookie("userid_");
    var playlistID = 0;
    //console.log("loginID = "+loginID);
    if (loginID > 0) {
        playlistID = readCookie("ActivePlaylist");
    }

    $.ajax({
        type: "POST",
        url: "PlaylistAgent.aspx/LoadPlayList",
        data: "{'UserID_':'" + loginID + "', 'PlaylistId_' : '" + playlistID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        cache: false,
        success: function(msg) {
            //console.log("got success from ajax");
            var response, playListId, songsList;
            response = eval(msg.d);
            if (response == "" || response == undef) {
                //alert("keep playlist");
                return;
            }
            playListId = response[0];
            songsList = response[1];
            myPlayList = eval(songsList);

            displayPlayList();
            playItem = 0;
            $("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3);
            $("#jplqyer_song_title").html($("#jplayer_playlist_item_" + playItem).text());
            $("#jplayer_playlist_item_" + playItem).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");

            createCookie("ActivePlaylist", playListId, 5)
            createCookie("myPlayList", JSON.stringify(myPlayList), 5);
        },
        error: function() {
            //alert("Request can’t made using ajax");
        }
    });        //ajax ends here

} //function ends


function SavePlayList() {
    if (pl_modified == true) {
        $(".jp-message").html("<p>Saving</p>").show();
        var loginID = readCookie("userid_");
        var playlistID = 0;
        var allsongs = JSON.stringify(myPlayList);

        if (loginID > 0) {
            playlistID = readCookie("ActivePlaylist");
        }

        $.ajax({
            type: "POST",
            url: "PlaylistAgent.aspx/Save",
            data: "{'userId_':'" + loginID + "', 'playListId_' : '" + playlistID + "', 'playlist':'" + allsongs + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            cache: false,
            success: function(msg) {
                //console.log("got success from ajax");
                if (msg.d == true) {
                    $(".jp-message").html("<p>Successfully Saved.</p>").show();
                    pl_modified = false;
                }
                else if (msg.d == false) {
                    $(".jp-message").html("<p>An error occured while saving playlist.</p>").show();
                }

            },
            error: function() {
                //alert("Request can’t made using ajax");
            }
        });      //ajax ends here

    }
    else {
        //do nothing
        $(".jp-message").html("<p>Playlist already saved.</p>").show();
    }


} //function ends

/*  Jplayer global functions ends here
---------------------------------------------------------------------------*/

function RestrictTyping(maxL, fld, counterID) {


    if (fld.value.length > maxL) {

        fld.value = fld.value.substring(0, maxL);

    }
    else {
        if (document.getElementById(counterID)) {

            document.getElementById(counterID).innerHTML = maxL - fld.value.length;
        }
    }

}

function setCharacters() {

    var ArgArr = setCharacters.arguments;
    var TotalItems = ArgArr.length;
    if (TotalItems > 0) {
        if (TotalItems % 3 == 0) {
            for (lv = 0; lv < TotalItems; lv += 3) {
                if (document.getElementById(ArgArr[lv])) {
                    RestrictTyping(ArgArr[lv + 2], document.getElementById(ArgArr[lv]), ArgArr[lv + 1])
                }
            }
        }
        else {
            alert("setCharacters -> Please pass arguments in pairs.")
        }
    }
    else {
        alert("setCharacters -> Please pass set(s) of 3 arguments in each (textareaid, counterid, max length...).")
    }
}

function GetQueryString(url, qryParm) {
    //alert("dfd");
    var qrStr = url.toLowerCase(); //window.location.search;
    var spQrStr = qrStr.substring(1);

    alert(spQrStr);
    var arr = spQrStr.split("&");
    var arrQrStr = new Array();
    for (var i = 0; i < arr.length; i++) {
        var index = arr[i].indexOf("=");
        var key = arr[i].substring(0, index);
        var val = arr[i].substring(index + 1);
        arrQrStr[key] = val;

    }
    if (arrQrStr[qryParm] != null)
        return arrQrStr[qryParm];
    else
        return "";

}

function gup(name) {
    name = name.toLowerCase();
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href.toLowerCase());
    if (results == null)
        return "";
    else
        return results[1];
}


//function ApplyCufon() {
//    Cufon.replace('h1, h2, h3, article footer a, section footer a, ul.tabs li a.txt, ul.tabs li, .cf a', { hover: true });
//    Cufon.now();
//}
//ApplyCufon(); 
