﻿tb_pathToImage = "/images/loadingAnimation.gif";
var CanCloseSearchBox = true;
function PrepareToUpload(Loader, OwnerID)
{
    $(document).ready(function(){
	    var button = $('#ImageLoader'), interval;
	    var Gallery = $('#Gallery');
	    var Progress = $('#ProgressBar');
	    new Ajax_upload(button,{
		    action: '/Controls/ImageUploader.aspx?Owner=' + Loader + "&OwnerID=" + OwnerID + "&rnd=" + Math.random(), 
		    name: 'UploadedFile',
		    onSubmit : function(file, ext){
		        Progress.text('Ekleniyor');
			        this.disable();
			        interval = window.setInterval(function(){
				        var text = Progress.text();
				        if (text.length < 13){
					        Progress.text(text + '.');					
				        } else {
					        Progress.text('Ekleniyor');				
				        }
			        }, 200);
		    },
		    onComplete: function(file, response){
		        window.clearInterval(interval);
		        this.enable();
		        if(response != "0")
		        {
		            Progress.text('Eklendi.');
		            Gallery.append("<a style='position:relative; padding-right:2px;' id='" + response.replace(".","") + "' title='' href='/Data/Content/" + Loader + "/Images/Size2/" + response + "'><img src='/Data/Content/" + Loader + "/Images/Size1/" + response + "' border='0' height='100px;'></a>");
		            $(function() {$('#Gallery a').lightBox({fixedNavigation:true});});
		        }
		        else
		        {
		            Progress.text('HATA: Dosya sisteme eklenemedi!');
		        }
		    }
	    });
    });
}

function FormatText(Text)
{
    while(Text.indexOf('&') > -1)
        Text = Text.replace("&", "%26");
    return Text;
}

function PrepareToComment(Owner, OwnerID, Parameters)
{
        $(document).ready(function(){
        $("#CommentSubmitButton").unbind("click");
        $("#CommentSubmitButton").click(function() {
        var Gallery = $('#CommentList');
	    if($('#CommentBody').val() == "")
	        return;
	    $.ajax({
          type: "POST",
          cache: false,
          url: "/Controls/Commenter.aspx",
          data: "Owner=" + Owner + "&rnd=" + Math.random() + "&OwnerID=" + OwnerID + "&Body=" + FormatText($('#CommentBody').val()) + "&Title=" + $('#CommentTitle').val() + "&" + Parameters,
          beforeSend: function(XMLHttpRequest) {
                $('#NewComment').fadeOut("slow");
                ShowLoadingAnimation("CommentProgressBar");
          },
          success: function(response) {
            Gallery.append(response);
            $("#AddedComment").hide();
            $("#AddedComment").fadeIn("slow");
            SetElements();
            HideLoadingAnimation("CommentProgressBar");
            if($('#CommentCount'))
            {
                $('#CommentCount').html($('#CommentCount').html() * 1 + 1);
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown){
            alert('Hata olustu! Lutfen daha sonra tekrar deneyiniz.');
          }
         });
      });
    }); 
    return false;
}

function ConfirmAndRedirect(A)
{
    var Title = A.getAttribute('title');
    if(Title == "" || Title == null)
        Title = "Silmek istediginize emin misiniz?";
    $(".CustomBoxes").remove();
    var OnClickFunction = "onclick=\"document.location.href='" + A.getAttribute('href') + "';\"";
    var Box = "<div class='CustomBoxes' id='DeleteConfirmationBox' style='display:none; text-align:center; color:#000000;'>" + Title + "<br><br><input type='button' class='Marker' " + OnClickFunction + "value='devam' style='width:60px;'>&nbsp;&nbsp;<input type='button' style='width:60px;' onclick='$.facebox.close();' class='Marker' value='iptal'></div>";
    $(Box).insertAfter($('#ConstantPanel'));
    $.facebox({div:'#DeleteConfirmationBox'}, 'my-groovy-style');
    $.facebox.hideFooter();
    return false;
}

function ConfirmDelete(A)
{
    var Title = A.getAttribute('title');
    if(Title == "" || Title == null)
        Title = "Silmek istediginize emin misiniz?";
    $(".CustomBoxes").remove();
    var OnClickFunction = "";
    if(A.getAttribute('func') != "")
        OnClickFunction = "onclick=\"" + A.getAttribute('func') + "\('" + A.href + "', '" + A.getAttribute('container') + "');\"";
    var Box = "<div class='CustomBoxes' id='DeleteConfirmationBox' style='display:none; text-align:center; color:#000000;'>" + Title + "<br><br><input type='button' class='Marker' " + OnClickFunction + "value='devam' style='width:60px;'>&nbsp;&nbsp;<input type='button' style='width:60px;' onclick='$.facebox.close();' class='Marker' value='iptal'></div>";
    $(Box).insertAfter($("#" + A.getAttribute('container')));
    $.facebox({div:'#DeleteConfirmationBox'}, 'my-groovy-style');
    $.facebox.hideFooter();
    return false;
}

function HideComment(href, Panel)
{
    Submit(href, "", "", "", false);
    $("#" + Panel).hide("slow");
    $.facebox.close();
}

function PrepareToEditComment(Owner, OwnerID, ID)
{
        $(document).ready(function(){
        $("#EditCommentSubmitButton").unbind("click");
        $("#EditCommentSubmitButton").click(function() {
        var Gallery = $('#CommentList');
	    var interval;
	    if($('#EditCommentBody').val() == "")
	        return;
	    $.ajax({
          type: "POST",
          cache: false,
          url: "/Controls/Commenter.aspx",
          data: "Owner=" + Owner + "&rnd=" + Math.random() + "&ID=" + ID + "&OwnerID=" + OwnerID + "&Body=" + FormatText($('#EditCommentBody').val()) + "&Action=Edit&Submitted=1&Title=" + $('#EditCommentTitle').val(),
          beforeSend: function(XMLHttpRequest) {
                $('#EditComment').fadeOut("slow");
                ShowLoadingAnimation("EditCommentProgressBar");
          },
          success: function(response) {
            if(response != "0")
            {
                $("#Comment_" + ID).fadeOut("slow");
                $("#Comment_" + ID).attr("id", "Ex_Comment_" + ID);
                $(response).insertAfter("#Ex_Comment_" + ID);
                $("#Ex_Comment_" + ID).remove();
                $("#Comment_" + ID).fadeIn("slow");
                SetElements();
                $.facebox.close();
            }
            else
            {
                HideLoadingAnimation("EditCommentProgressBar");
                $.facebox.close();
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown){
            alert('Hata olustu! Lutfen daha sonra tekrar deneyiniz.');
          }
         });
      });
    }); 
    return false;
}

function Rate(Owner, OwnerID, Point, Suffix, Type)
{
    $.ajax({
      type: "POST",
      cache: false,
      url: "/Controls/Evaluator.aspx",
      data: "Owner=" + Owner + "&OwnerID=" + OwnerID + "&Type=" + Type + "&rnd=" + Math.random() + "&Point=" + Point
     });
     for(i=1; i <= 10; i++)
     {
        if(Point >= i)
            document.getElementById("Point" + i + Suffix).style.backgroundColor = "#182A36";
        else
            document.getElementById("Point" + i + Suffix).style.backgroundColor = "#FFFFFF";
     }
    PointColor = "#182A36";
    if(Owner == "Movie" && Type == 0)
    {
        if($("#SubmitPopup")) {$("#SubmitPopup").remove();}
        $("<div id='SubmitPopup' style='display:none; text-align:center; color:#000000;'></div>").insertAfter($("#ConstantPanel"));
        $.facebox({div:'#SubmitPopup'}, 'my-groovy-style');
        $.facebox.hideFooter();
        $("#SubmitPopup").html("Film, izledikleriniz listesine de eklendi.<br><br><input id='SubmitPopup_OK' type='button' style='width:60px;' onclick='$.facebox.close();' class='Marker' value='Tamam'>");
        $('#SubmitPopup_OK').focus();
        PrepareFaceboxToClose();
    }
    return false;    
}

function SubmitWithPopup(URL, dataString, Message)
{
    if($("#SubmitPopup")) {$("#SubmitPopup").remove();}
    $("<div id='SubmitPopup' style='display:none; text-align:center; color:#000000;'></div>").insertAfter($("#ConstantPanel"));
    if(URL.indexOf('?') == -1)  
        URL = URL + '?';
    if(URL.indexOf("rnd=") == -1)
        URL = URL + "&rnd=" + Math.random();
    ShowLoadingAnimation("SubmitPopup");
    $.facebox({div:'#SubmitPopup'}, 'my-groovy-style');
    $.facebox.hideFooter();
    $.ajax({
      type: "POST",
      cache: false,
      url: URL,
      data: dataString,
      success: function(response) {
        $("#SubmitPopup").html(Message + "<br><br><input id='SubmitPopup_OK' type='button' style='width:60px;' onclick='$.facebox.close();' class='Marker' value='Tamam'>");
        $('#SubmitPopup_OK').focus();
        PrepareFaceboxToClose();
      },
      error: function (XMLHttpRequest, textStatus, errorThrown){
        $("#SubmitPopup").html("İşlem bir hata ile karşılaştı. Yaşanan aksaklıktan dolayı özür dileriz.<br><br><input type='button' style='width:50px;' onclick='$.facebox.close();' class='Marker' value='Tamam'>");
        PrepareFaceboxToClose();
      }
     });
    return false;
}

var FaceboxTimer;
function PrepareFaceboxToClose()
{
    FaceboxTimer = setTimeout("CloseFacebox()", 2000)
}

function CloseFacebox()
{
    if(FaceboxTimer)
        clearTimeout(FaceboxTimer);
    $.facebox.close();
}

function Submit(URL, dataString, ProgressBar, PanelToAppend, Animate)
{
    if(URL.indexOf('?') == -1)  
        URL = URL + '?';
    if(URL.indexOf("rnd=") == -1)
        URL = URL + "&rnd=" + Math.random();
    $.ajax({
      type: "POST",
      cache: false,
      url: URL,
      data: dataString,
      success: function(response) {
        if(ProgressBar != "")
        {
            var Progress = $('#' + ProgressBar);
            if(Animate == false)
                Progress.text("");
            else
                ShowLoadingAnimation(ProgressBar);
            if(response != "0")
            {
                if(Animate == false)
                    Progress.text('Eklendi.');
                if(PanelToAppend != "") 
                {
                    if(Animate == false)
                        $('#' + PanelToAppend).append(response);
                    else
                    {
                        if(response != null && response != "" && response != "1")
                        {
                            var ID = "ID_" + Math.random();
                            ID = ID.replace(".","").replace(",","");
                            $('#' + PanelToAppend).append("<div id='" + ID + "' style='display:none;'>" + response + "</div>");
                            $("#" + ID).fadeIn("slow");
                            SetElements();
                        }
                    }
                }
                if(Animate == true)
                    HideLoadingAnimation(ProgressBar);
            }
            else
            {
                Progress.text('HATA: Sistemde hata olustu!');
            }
        }
        $.facebox.close();
      },
        error: function (XMLHttpRequest, textStatus, errorThrown){
            //alert(errorThrown);
        }
     });
    return false;
}

var PointColor = "";
function HighlightPoint(TD, Point)
{
    PointColor = TD.style.backgroundColor;
    TD.style.backgroundColor = '#182A36';
    TD.innerHTML = Point;
}
function UnhighlightPoint(TD)
{
    TD.style.backgroundColor = PointColor;
    TD.innerHTML = "&nbsp;";
}

function SetText(d,a,b)
{
    var o=document.getElementById(d);
    o.focus();
    if(document.selection && !window.opera)
    {
      var rg=document.selection.createRange();
      if(rg.parentElement()==o) {
          rg.text = a+rg.text+b;
          rg.select();
        } else alert("önce işaretlemek için metin seçin.");
    }
    else if(o.selectionStart||o.selectionStart=='0')
    {
        var s = o.value;
        var end = o.selectionEnd;
        var start = o.selectionStart;
        o.value = s.substring(0,start)+a+s.substring(start,end)+b+s.substring(end);
        end += a.length+b.length;
        o.setSelectionRange(end, end);
    } else o.value += a+b;
    return true;
}

function HideLoadingAnimation(Container)
{
    var C = $("#" + Container);
    C.html("");
}
function ShowLoadingAnimation(Container)
{
    var C = $("#" + Container);
    C.html("<img src='/Data/Design/LoadingAnimation.gif' border=0>");
}

function LoadPanel(Panel, Href)//Bir paneli blok halinde yukler, loading animasyonunu bu panel icerisinde gosterir.
{
    ShowLoadingAnimation(Panel);
    var P = $("#" + Panel);
    if(Href.indexOf('?') == -1)
        Href = Href + "?";
    $.ajax({
      cache: false,
      type: "POST",
      url: Href + "&Ajax=1&rnd=" + Math.random(),
      data: "",
      success: function(response) {
        P.html(response);
        P.hide();
        P.show();
        SetElements();
      },
      error: function (XMLHttpRequest, textStatus, errorThrown){
        HideLoadingAnimation(Panel);
      }
     });
    return false;
}

function SetSubTabsHandlers()
{
    $(document).ready(function(){ 
    $(".SubTabs .SubTab").unbind("click");
    $(".SubTabs .SubTab").click( 
        function() {
            if(this.className.indexOf('NoAjax') == -1 &&  this.href != "" &&  this.href != null &&  this.href != undefined)
            {
                $(".SubTabs .SubTab").css({fontWeight:""}); 
                $(this).css({ fontWeight:"bold"}); 
                LoadPanel('SubContent', this.href);
                return false;
            }
        });
    });
}

function SetSpoilerAppearence()
{
    $(document).ready(function(){ $("div.DisabledSpoilerAtComment").unbind("mouseover").unbind("mouseout"); $("div.DisabledSpoilerAtComment").mouseover(function(){ this.className = 'EnabledSpoilerAtComment'; }).mouseout(function(){ this.className = 'DisabledSpoilerAtComment'; }); });
}

function BindFaceboxElements()
{
    jQuery(document).ready
    (
        function($) 
        {
          $('a[rel*=facebox]').each(
            function (){
                $(this).unbind("click");
                $(this).click(function(){ $.facebox({ajax:this.href}, 'my-groovy-style'); return false;});
            }
          );
          $('a[box*=Delete]').each(
            function (){
                $(this).unbind("click");
                $(this).click(function(){ ConfirmDelete(this); return false;});
            }
          );
          $('a[rel*=Video]').each(
            function (){
                $(this).unbind("click");
                $(this).click(function(){$.facebox({ajax:"/Controls/VideoViewer.aspx?URL=" + this.href}, 'my-groovy-style');return false;});
            }
          );
        }
    );
}

function SetElements()
{
    SetSpoilerAppearence();
    SetSubTabsHandlers();
    BindFaceboxElements();
}

function SetAutoComplete()
{
    jQuery(document).ready
    (
        function($) 
        {
            $(".CharacterAutoComplete").autocomplete('/Search.aspx?Ajax=1&Type=Char', {width: 300, multiple: true, matchContains: true });
            $(".PlayerAutoComplete").autocomplete('/Search.aspx?Ajax=1&Type=Player&Add=Player', {width: 300, multiple: false, matchContains: true});
            $(".DirectorAutoComplete").autocomplete('/Search.aspx?Ajax=1&Type=Player&Add=Director', {width: 300, multiple: false, matchContains: true});
        }
    );
}

function MakeAccordion(P)
{
    jQuery(document).ready
    (
        function()
        {
            var Panel = $('#' + P);
            var Height = 0;
            var Counter = 0;
            $('#' + P + " div").each(
                function(){
                if(Counter > 0)
                    $(this).hide();
                Counter++;
            });
            $('#' + P + " a").click(function() 
                { 
                    $('#' + P + " div").hide(); $(this).next().slideDown('slow'); 
                }
            );
        }
    )
}

function SelectTab(TabsPanel, Panel, A)
{
    $("#" + TabsPanel + " a").removeClass('NotSelectedTab');
    $("#" + TabsPanel + " a").removeClass('SelectedTab');
    $("#" + TabsPanel + " a").addClass('NotSelectedTab');
    $(A).addClass('SelectedTab');
    LoadPanel(Panel, A.href);
    return false;
}

var NewPlayerCounter = 0;
function CreatePlayer(Type)
{
    var Panel;
    var NewPlayer;
    if(Type == "Director")
    {
        Panel = $("#Directors");
        NewPlayer = $("#NewDirector");
        }
    else
    {
        Panel = $("#Players");
        NewPlayer = $("#NewPlayer");
        }
    Panel.append("<tr><td><input type='hidden' name='PlayerType_" + NewPlayerCounter + "' value='" + Type + "'><input type='hidden' value=\"" + NewPlayer.val() + "\" name='NewPlayer_" + NewPlayerCounter + "'>" + NewPlayer.val() + "</td><td><input type='text' name='NewCharacterName_" + NewPlayerCounter + "' style='width:150px;'></td><td><input type='text' name='NewSortOrder_" + NewPlayerCounter + "' style='width:50px;'></td><td></td><td></td></tr>");
    NewPlayer.val("");
    NewPlayerCounter++;
}

function EvaluateComment(OwnerID, CommentID, Owner, Type)
{
    if($('#CommentPanel_' + CommentID + "_Status").html() == null || $('#CommentPanel_' + CommentID + "_Status").html() == "")
    {
        var sType = "";
        if(Type == 1)
        {
            sType = "Like";
            $('#CommentPanel_' + CommentID + "_Status").html("<i>(Bu yorumu sevdiniz)</i><br>");
        }
        else
        {
            sType = "Dislike";
            $('#CommentPanel_' + CommentID + "_Status").html("<i>(Bu yorumu sevmediniz)</i><br>");
        }
        Submit("/Controls/Commenter.aspx?ID=" + CommentID + "&Action=" + sType + "&Owner=" + Owner + "&OwnerID=" + OwnerID, "", "", "", false);
        $('#CommentPanel_' + CommentID + "_Status").slideToggle("slow");
    }
}

function Search(t, e)
{
    var Navigate = false;
    if(e == 0)
    {
        if(t == 5)
            document.location.href='/Content/Discussion/Title.aspx?q=' + $('#SearchBox').val();
        else
            document.location.href='/Search.aspx?t=' + t + "&q=" + $('#SearchBox').val();   
    }
    else
    {
        var Curr = 0;
        var Index = 0;
        var Select = false;
        $(".DetailedSBRow").each(
            function(){ Index++; if(this.className.indexOf('SelectedSearchBox') > -1) { Curr = Index; return;}}
        );
        if ((event.which == 13) || (event.keyCode == 13)) 
        {
            Navigate = true;
        }
        else if ((event.which == 38) || (event.keyCode == 38)) 
        {
            Select = true;
            if(Curr > 0)
                Curr = Curr - 1;
            else
                Curr = Index - 1;
        }
        else if ((event.which == 40) || (event.keyCode == 40)) 
        {
            Select = true;
            if(Curr <= Index)
                Curr = Curr + 1;
            else
                Curr = 1;
        }
        var Index = 0;
        if(Curr > 0)
        {
            $(".DetailedSBRow").each(
                function(){ Index++; if(Curr == Index) { $(this).addClass('SelectedSearchBox');} else {$(this).removeClass('SelectedSearchBox');} }
            );
        }
        if(Navigate && Curr > 0 && Curr < 5)
            document.location.href='/Search.aspx?t=' + Curr + "&q=" + $('#SearchBox').val();
        else if(Navigate && Curr == 5)
            document.location.href='/Content/Discussion/Title.aspx?q=' + $('#SearchBox').val();
    }    
}

function DetailedSearchBox()
{
    var Value = "deneme";
    if(!document.getElementById('DetailedSearchBox'))
    {
        var Left = $('#SearchBox').offset().left;
        var Top = $('#SearchBox').offset().top + document.getElementById('SearchBox').offsetHeight;
        Value = "<div id='DetailedSearchBox' class='DetailedSearchBox' onmouseover='CanCloseSearchBox = false;' onmouseout='CanCloseSearchBox = true;' style='position:absolute; z-index:99; left:" + Left + "; top:" + Top + "; cursor:pointer;'><table cellspacing=0 cellpadding=4 style='width:" + ($('#SearchBox').width() + 10) + "px;'>";
        Value = Value + "<tr><td class='DetailedSBRow' onclick='Search(1, 0)'><span class='DetailedSBParam' style='font-weight:bold;'></span> &nbsp; filmlerde ara</td></tr>";
        Value = Value + "<tr><td class='DetailedSBRow' onclick='Search(2, 0)'><span class='DetailedSBParam' style='font-weight:bold;'></span> &nbsp; oyuncularda ara</td></tr>";
        Value = Value + "<tr><td class='DetailedSBRow' onclick='Search(3, 0)'><span class='DetailedSBParam' style='font-weight:bold;'></span> &nbsp; uyelerde ara</td></tr>";
        Value = Value + "<tr><td class='DetailedSBRow' onclick='Search(4, 0)'><span class='DetailedSBParam' style='font-weight:bold;'></span> &nbsp; karakterlerde ara</td></tr>";
        Value = Value + "<tr><td class='DetailedSBRow' onclick='Search(5, 0)'><span class='DetailedSBParam' style='font-weight:bold;'></span> &nbsp; açık görüşte ara</td></tr>";
        Value = Value + "</table></div>";
        $(Value).insertAfter('#SearchBox');
        $('.DetailedSBRow').mouseover(function() {$(this).addClass('SelectedSearchBox');})
        $('.DetailedSBRow').mouseout(function() {$(this).removeClass('SelectedSearchBox');})
    }
}

function SubmitThought()
{
    //$("#WriteThought").fadeOut("slow");
    Submit("/Broadcast.aspx?Ajax=1", "Thought=" + FormatText($('#Thought').val()), "ThoughtProgress", "NewThoughts", true);
    $("#Thought").val("");
}

var FeedTimer;
var LoadingFeeds = false;
var LastFeedUpdate;
function UpdateFeeds()
{
    if(!IsFaceboxShown && document.getElementById("NewThoughts"))
    {
        if(!LoadingFeeds)
        {
            LoadingFeeds = true;
            Submit("/Broadcast.aspx?Ajax=1&NewFeeds=1", "", "ThoughtProgress", "NewThoughts", true);
            LoadingFeeds = false;
        }
    }
    if(FeedTimer)
            clearTimeout(FeedTimer);
    FeedTimer = setTimeout("UpdateFeeds()", 10000);
}

$(document).ready(function(){
    $('#Thought').autoResize();
    UpdateFeeds();
})

jQuery(document).ready
(
    function($) 
    {
        $('#SearchBox').focus( function() { DetailedSearchBox(); $('#DetailedSearchBox').show(); } );
        $('#SearchBox').blur( function() { if(CanCloseSearchBox) {$('#DetailedSearchBox').hide(); $('.DetailedSBParam').attr('bgcolor', '');}});
        $('#SearchBox').keyup( function() { $('.DetailedSBParam').html($('#SearchBox').val()); Search(0, 1); } );
    }
);