﻿
(function ($) {
    $.fn.customFadeIn = function (speed, callback) {
        $(this).fadeIn(speed, function () {
            if (jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if (callback != undefined)
                callback();
        });
    };
    $.fn.customFadeOut = function (speed, callback) {
        $(this).fadeOut(speed, function () {
            if (jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if (callback != undefined)
                callback();
        });
    };
})(jQuery);


var flag;
var timer_is_on = 1;
var t;
var page = 1;
var counter = 0;
var prev = false;

//Header
function stbhiNext() {
    var current = parseInt($('.stbhi_pgr a.stbhi_active').attr('rel'));
    var count = $('.stbhi_pgr a').length;
    if (prev && current - 1 < 0) {
        prev = false;
        $('.stbhi_pgr a.stbhi_active').parent().next().children(0).trigger('click');
    }
    else
        if (current + 1 < count)
            if (prev)
                $('.stbhi_pgr a.stbhi_active').parent().prev().children(0).trigger('click');
            else
                $('.stbhi_pgr a.stbhi_active').parent().next().children(0).trigger('click');
        else {
            prev = true;
            $('.stbhi_pgr a.stbhi_active').parent().prev().children(0).trigger('click');
        }
    SetTimer();
}

function LoadWork() {
    if (document.location.hash.split('work').length > 1) {
        var selectedWorkId = document.location.hash.split('work')[1];
        var selectedWork = $('.thumb').find('input.hfId:[value="' + selectedWorkId + '"]');
        if (selectedWork.length > 0) {
            selectedWork.parent().click();
        }
    }
    $('.nav a').removeClass('active'); $('.nav a[title="Our work"]').addClass('active');
}
function LoadNewsId(id) {

    document.location.hash = "#news" + id;
    LoadNews();
}

function LoadNews() {
    
    var newsId = 0;
    if (document.location.hash.split('news').length > 1) {
        newsId = document.location.hash.split('news')[1];
        $('.nav a').removeClass('active'); $('.nav a[title="News"]').addClass('active');
        $.scrollTo({ top: $('#news').offset().top - 145, left: $('#news').offset().left }, 1700);
    }
    else {
        newsId = $('.news-block .read-more:first').attr('rel');
    }
    getNews(newsId);
    setActive($('.read-more[rel="' + newsId + '"]'));
}

function SetTimer() {
    if (timer_is_on) { clearTimeout(t); }
    else { timer_is_on = 1; }
    t = setTimeout('stbhiNext()', 10000);
}
function RemoveTimer() {
    if (timer_is_on) {
        timer_is_on = 0;
        clearTimeout(t);
    }
}

//TM-work
function SelectWork() {
    if ($('.preloader').height() == 0) {
        $('.preloader').animate({ opacity: 0.5, height: $(document).height() }, 300);
        $('.preloader img').animate({ top: parseInt((($(window).height() - $('.preloader img').height()) / 2) + $(document).scrollTop()+ 150) + "px" }, 100);
    }

    var index = $('.work-trio .thumb').index(this);
    var oldIndex = $('a.selected').parents('.thumb').index();
   var IsIncrHeight = parseInt(index / 4) > parseInt(oldIndex / 4) ? true : false;
   
    var itemDescription = $('li.descriptionLi');
    var selectedLink = $(this).parent().find('li a.selected');
    var isClose = $(this).find('a.selected').length > 0;

    var id = $(this).find('.hfId').val();

    var selectedLinkHTML = '<a title="Click to close" style="display: none;" class="selected"></a>';

    var incr = parseInt(index % 4);
    index += parseInt(3 - incr);
    
    
    var maxIndex = parseInt($('.thumb').length - 1);
    if (index > maxIndex) index = maxIndex;
    var time = isClose ? 200 : 100;

    $('.col-wrapper ').height(0);

    if (selectedLink.length > 0) {
        selectedLink.addClass('removed');
        selectedLink.fadeOut(100, function () {
            selectedLink.remove();
        });
    }
    if (!isClose) {
        $(selectedLinkHTML).insertAfter($(this).find('a.link'));
        $('a.selected').not('.removed').fadeIn(time, function () {
            if (IsIncrHeight) {
                $.scrollTo({ top: $(this).offset().top - 155 - itemDescription.height(), left: $('#workpieces').offset().left }, 100);
            }
            else {
                $.scrollTo({ top: $(this).offset().top - 155, left: $('#workpieces').offset().left }, 100);
            }
        });
        document.location.hash = "#work" + id;
    }
    else {
        $.scrollTo({ top: $('.work-trio').offset().top - 155, left: $('#workpieces').offset().left }, 100, function () { $('.preloader').animate({ opacity: 0, height: 0 }, 300); });
        document.location.hash = null;
    }

    if (itemDescription.length > 0) {
        itemDescription.hide(800, function () {
            itemDescription.remove();
            if (!isClose) {
                var descLi = $('<li></li>').addClass('descriptionLi').css({ 'height': '0', 'clear': 'left' }).html($('.description-container').html())
                descLi.insertAfter($($('.thumb')[index]));
                getInfo(id);
            }
        });
    }
    else {
        if (!isClose) {
            var descLi = $('<li></li>').addClass('descriptionLi').css({ 'height': '0', 'clear': 'left' }).html($('.description-container').html())
            descLi.insertAfter($($('.thumb')[index]));
            getInfo(id);
        }
    }
}
function getInfo(id) {
    $.ajax({
        type: "POST",
        url: "/DesktopModules/TM-Work/WorksInfo.aspx/FindInfoAjax",
        data: "{strId:'" + id + "'}",
        contentType: "application/json; charset=utf-8",
        datatype: "jsondata",
        success: function (response) {
            if (response != null) {
                DisplayWorkInfo($.parseJSON(response.d));
            }
        },
        error: function (response) {
            // alert(response.status + " " + response.statusText);
        }
    });

}
function DisplayWorkInfo(object) {
    $('.descriptionLi').height(0);
    $('.descriptionLi .CampaignTitle').html(object.CampaignTitle);
    $('.descriptionLi .ClientTitle').html(object.ClientTitle);
    $('.descriptionLi .Description').html(object.Description);
    $('.descriptionLi .social').html(object.FacebookText + object.TweeterText);
    $('.descriptionLi .slider-controls').attr("id", "controls");
    $('.descriptionLi .slider').html(CreateSlider(object.Images)).attr("id", "slider");
    $('div.work_media').each(function (index, elem) {
        $(this).replaceWith(CreateVideoHtml($(this), 542, 224));
    });
    $('#slider').easySlider({
        auto: false,
        continuous: true,
        numeric: true,
        numericId: "controls"
    });
   
}
function CreateSlider(xml) {
    if (xml == "") return "";
    var _result = "";
    var html = "<ul>";
    if (jQuery.browser.msie) {
        data = new ActiveXObject('Microsoft.XMLDOM');
        data.async = false;
        data.loadXML(xml);
    } else {
        data = xml;
    }

    $('file', data).each(function (i, _item) {
        var imgHTML = "";
        if ($(_item)[0].attributes.length > 2) {
            imgHTML = '<div class="work_media"><a class="poster" id="wm_' + i + '" href="' + $(_item).text() + '"></a>' +
        '<a class="mp4" href="http://' + location.host + $(_item)[0].attributes.getNamedItem("video_mp4").value + '"></a>' +
        '<a class="ogv" href="http://' + location.host + $(_item)[0].attributes.getNamedItem("video_ogv").value + '"></a>' +
        '<a class="webm" href="http://' + location.host + $(_item)[0].attributes.getNamedItem("video_webm").value + '"></a></div>';
            _result += '<li style="text-align:center;">' + imgHTML + '</li>';
        }
        else {
            imgHTML = '<img alt="" src="' + $(_item).text() + '"/>';
            _result += '<li style="text-align:center;"><a >' + imgHTML + '</a></li>';
        }


        imgHTML = "";
    });
    html += _result;
    html += "</ul>";
    return html;
}

function DeleteField(field) {
    //    jQuery.get("/DesktopModules/TM-Work/Handler/WorkHandler.ashx?field=" + field + "&href=" + window.location.href);
    jQuery.get("/DesktopModules/TM-Work/Handler/WorkHandler.ashx?field=" + field + "&href=" + window.location.href, function (data) {
        window.location.href = "/";
    });
}

//TM-news
function LoadNextPage(pageLink) {
    $('.navi .pagerLink').removeClass("act");
    var pageNum = 1;
    if (pageLink != null) {
        pageNum = $(pageLink).text();
        page = pageNum;
        $(pageLink).addClass("act");
    }
    getPage(pageNum);
}
function getPage(num) {
    $.ajax({
        type: "POST",
        url: "/DesktopModules/Blog/TMNewsInfo.aspx/GetPageAjax",
        data: "{page:'" + num + "', portalID:'" + $('[id$=hfPortal]').val() + "'}",
        contentType: "application/json; charset=utf-8",
        datatype: "jsondata",
        success: function (response) {
            if (response != null) {
                DisplayPage($.parseJSON(response.d));
            }
        },
        error: function (response) {
            //  alert(response.status + " " + response.statusText);
        }
    });
}
function DisplayPage(object) {
    $('#news-box .news-block').fadeOut('fast', function () {
        $('#news-box .news-block').remove();
        var html = "";
        for (var i = 0; i < object.length; i++) {
            html += "<div class='news-block' style='display:none;'>";
            if ($("#hfEdit").val()) {
                html += '<div class="controls" style="width:20px;float:left;">' +
            '<a href="/Home/tabid/41/ctl/Edit_Entry/mid/406/BlogID/1/EntryID/' + object[i].EntryID + '/Default.aspx" onclick="return true;"><img src="../../images/edit.gif" alt="edit" /></a>' +
            '<a onclick="javascript:deleteEntry(' + object[i].EntryID + ');"><img alt="Delete" src="/images/delete.gif"></a>' +
            '</div>';
            }
            html += '<h1>'
            + object[i].Title + '</h1><p>' + object[i].Description
            + ' ... <a class="read-more" title="read more &raquo;" rel="' + object[i].EntryID + '" onclick="javascript:LoadNewsId(' + object[i].EntryID + ');" >read more »</a></p><span class="posted">Posted '
            + $.format.date(new Date(parseInt(object[i].AddedDate.substr(6))), "MMM dd, yyyy")
            + '</span></div>';
        };
        $(html).appendTo($('#news-box'));
        $('#news-box .news-block').fadeIn('fast');
        $('.read-more:first').click();
    });
}

function getNews(id) {
    $.ajax({
        type: "POST",
        url: "/DesktopModules/Blog/TMNewsInfo.aspx/GetNewsAjax",
        data: "{newsId:'" + id + "', portalID:'" + $('[id$=hfPortal]').val() + "'}",
        contentType: "application/json; charset=utf-8",
        datatype: "jsondata",
        success: function (response) {
            if (response != null) {
                DisplayNews($.parseJSON(response.d));
            }
        },
        error: function (response) {
            //  alert(response.status + " " + response.statusText);
        }
    });
}
function DisplayNews(object) {
    if (object == null) return;
    $('.col6').fadeOut('fast', function () {
        $('.col6 .content h1').html(object.Title);
        $('.col6 .content .post').html("Posted " + object.Date);
        $('.col6 .content .description').html(object.Entry);
        $('.col6').fadeIn('fast');
    })
}
function deleteEntry(id) {
    $.ajax({
        type: "POST",
        url: "/DesktopModules/Blog/TMNewsInfo.aspx/DeleteEntryAjax",
        data: "{newsId:'" + id + "', page:'" + page + "', portalID:'" + $('[id$=hfPortal]').val() + "'}",
        contentType: "application/json; charset=utf-8",
        datatype: "jsondata",
        success: function (response) {
            if (response != null) {
                DisplayPage($.parseJSON(response.d));
            }
        },
        error: function (response) {
            // alert(response.status + " " + response.statusText);
        }
    });

}
function setActive(elem) {
    $('.news-block').removeClass('act');
    $(elem).parents('.news-block').addClass('act');
}

function Preload() {
   $('.preloader img').css("top", parseInt((($(window).height() - $('.preloader img').height()) / 2) + $(document).scrollTop()) + "px");
    $('.preloader').animate({ opacity: 0.5, height: $(document).height() }, 300);
    $('img').imgpreload
({
    each: function () {
    },
    all: function () {
        $('.preloader').animate({ opacity: 0, height: 0 }, 300);
    }
});
}

//page load
//header

function CreateVideoHtml(obj, width, heigth) {
    var videoHTML = '<div class="video-js-box" >' +
    '<video id="video_' + obj.find('.poster').attr('id') + '" class="video-js" width="' + width + '" height="' + heigth + '"  controls  poster="' + obj.find('.poster').attr('href') + '">' +
      ' <source src="' + obj.find('.mp4').attr('href') + '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />' +
      ' <source src="' + obj.find('.webm').attr('href') + '" type=\'video/webm; codecs="vp8, vorbis"\' />' +
      ' <source src="' + obj.find('.ogv').attr('href') + '" type=\'video/ogg; codecs="theora, vorbis"\' />' +
      ' <object name ="flash_' + obj.find('.poster').attr('id') + '" id="flash_' + obj.find('.poster').attr('id') + '" class="vjs-flash-fallback" width="' + width + '" height="' + heigth + '" type="application/x-shockwave-flash"' +
        ' data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">' +
        ' <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />' +
        ' <param name="allowfullscreen" value="true" />' +
        ' <param name="wmode" value="opaque" />' +
        ' <param name="flashvars" value=\'config={"playlist":["' + obj.find('.poster').attr('href') + '", {"url": "' + obj.find('.mp4').attr('href') + '","autoPlay":false,"autoBuffering":false}]}\' />' +
       ' <img src="' + obj.find('.poster').attr('href') + '" width="' + width + '" height="' + heigth + '"   alt="Poster Image"' +
         ' title="No video playback capabilities." />' +
              ' </object></video></div>';
    return videoHTML;
}


$(document).ready(function () {
    Preload();
    $('div.media').each(function (index, elem) {
        $(this).html(CreateVideoHtml($(this), 600, 340));
    });
    VideoJS.setupAllWhenReady();

    $('.stbhi_pgr a').bind('click', function () {
        SetTimer();
        $('.stbhi_pgr a').toggleClass('stbhi_active', false);
        $(this).toggleClass('stbhi_active', true);
        var pos = 960 * parseInt($(this).attr('rel'));

        // Scroll effect
        $('.stbhi_tbl').animate({ left: '-' + pos + 'px' }, 500);

        // Fade effect
        try {
            $('.media .video-js').each(function () {
                if (!$(this)[0].player.paused()) {
                    $(this)[0].player.pause();
                }
            });
        }
        catch (ex) {
        }
        
    });

    $('.learn-more').click(function () {
        var hash = $(this).attr('href');
        if (hash.split('work').length > 1) {
            if ($(this).attr('href') == location.href) {
                $('.nav a').removeClass('active'); $('.nav a[title="Our work"]').addClass('active');
                $.scrollTo({ top: $('#work').offset().top - 145, left: $('#work').offset().left }, 1700);
                return;
            }
            document.location.href = "#" + hash.split("#")[1];
            LoadWork();
            SetTimer();
            return false;
        }
        else {
            if (hash.split('news').length > 1) {
                document.location.hash = "#" + hash.split("#")[1];
                LoadNews();
                SetTimer();
                return false;
            }
        }
    });

    SetTimer();

    //work
    $('.thumb').bind('click', SelectWork);
    LoadWork();
    //blog
    LoadNews();
});


VideoJS.DOMReady(function () {
    $('.media .video-js').each(function () {
        var player = $(this).VideoJS().player();
        if (player != undefined) {
            player.onPause(function () {
                SetTimer();
            });
            player.onEnded(function () {
                SetTimer();
            });
            player.onPlay(function () {
                RemoveTimer();
            });
        }
    });
});
    


   
