﻿// Company: MakingWaves
// Component: MediaPlayer
// Author: Krzysztof Danielewicz, Kjetil Hansen

/*global $, Image*/

var makingWaves,
    onYouTubePlayerReady;
if (!makingWaves) {
    makingWaves = {};
} else if (typeof makingWaves !== "object") {
    throw new Error("makingWaves already exists and is not an object");
}

onYouTubePlayerReady = function(playerid) {

};

// size type = 1, 2, 3
makingWaves.MediaPlayer = function (id, sizeType) {
    "use strict";
    var self = this,
        counterRegexPattern = /^[(](\d*\/\d*)[)]$/,
        initializePreview;

    function shiftThumbnails(jqThumbnailsObj, numOfItem, forward, smallShift) {
        var shift = 84,
            direction = forward ? "-" : "+",
            animateSettings;
        if (numOfItem <= 0) {
            return;
        }
        if (smallShift) {
            shift = 58;
        }
        animateSettings = direction.toString() + "=" + (shift * numOfItem).toString() + "px";
        jqThumbnailsObj.animate(
                { left: animateSettings }, 400);

    }

    function dataFromRel(rel) {
        var d = rel.split(",", 4);
        return { "url": d[0], "desc": d[1], "a": d[2], "id": d[3] };
    }

    function bindVideoTmpl(jqSelLi) {
        var eWidth = 725,
        eHeight = 438;
        switch (self.sizeType) {
            case 1:
                eWidth = 475;
                eHeight = 297;
                break;
            case 2:
                eWidth = 642;
                eHeight = 391;
                break;

        }
        var rel = jqSelLi.find("a").attr("rel"),
            data = { "url": dataFromRel(rel).url, "width": eWidth, "height": eHeight },
            htmlTmpl = $.tmpl("videoTmpl", data),
            params = { allowScriptAccess: "always" },
            atts = { id: "myytplayer" };

        self.jqPreview.empty();
        htmlTmpl.hide();
        htmlTmpl.appendTo(self.jqPreview);
        htmlTmpl.fadeIn('fast');



        //swfobject.embedSWF("http://www.youtube.com/e/" + data.url.toString(),
        //               "ytembed", eWidth.toString(), eHeight.toString(), "8", null, null, params, atts);


        $('#photoThumbs').removeClass("active");
        $('#videoThumbs').addClass("active");

    }
    function updateVidCounter(num) {
        var jqCounter = self.jqConsole.find(".videocounter"),
            counterText = jqCounter.text(),
            splitedCounter;
        counterText = counterText.replace(counterRegexPattern, "$1");
        splitedCounter = counterText.split("/", 2);
        if (splitedCounter && splitedCounter.length === 2) {
            jqCounter.text("(" + num + "/" + splitedCounter[1] + ")");
        }
    }

    function updateImgCounter(num) {
        var jqCounter = self.jqConsole.find(".imagecounter"),
            counterText = jqCounter.text(),
            splittedCounter;
        counterText = counterText.replace(counterRegexPattern, "$1");
        splittedCounter = counterText.split("/", 2);
        if (splittedCounter && splittedCounter.length === 2) {
            jqCounter.text("(" + num + "/" + splittedCounter[1] + ")");
        }

    }
    function ChangeDescription(data) {

        //var d = data.photo.description._content.split(";", 2);
        var d = data.split(";", 2);
        ChangeDescriptionLocal(d[0], d[1])

    }
    function ChangeDescriptionLocal(desc, credits) {
        $("#caption").text(desc);
        if ($("#caption").text().length > 0) {
            $("#caption").show();
        }
        else {
            $("#caption").hide();
        }

        if (credits != null && credits.length > 0) {
            $("#photocreditText").text(credits);
            $("#photocreditLabel").show();
        }
        else {
            $("#photocreditLabel").hide();
            $("#photocreditText").text("");
        }

    }
    function flickr_test() {
        var apiKey = 'YOUR_API_KEY';
        $.ajax({
            url: 'http://api.flickr.com/services/rest/',
            data: {
                method: 'flickr.test.echo',
                api_key: 'dfb0557e6efa7a745d0b005fc66273c1',
                format: 'json',
                test: 'test string',
                jsoncallback: 'jsonFlickrApi'
            },
            dataType: 'jsonp'
        });
    }
    function jsonFlickrApi(response) {
        alert("aa");
    }
    function bindImageTmpl(jqSelectedThumbLi) {

        var rel = jqSelectedThumbLi.find("a").attr("rel"),
        data = dataFromRel(rel),
        htmlTmpl = $.tmpl("photoTmpl", data);

        self.jqPreview.empty();
        htmlTmpl.hide();
        htmlTmpl.find("#photocreditLabel").hide();
        htmlTmpl.find("#caption").hide();
        htmlTmpl.appendTo(self.jqPreview);
        htmlTmpl.show();

        if (data.id.length > 0) {
            $.ajaxSetup({ cache: false });
            $.ajax({
                type: 'GET',
                url: '/SocialHandler.ashx',
                dataType: 'text',
                data: {
                    photo_id: data.id
                },
                success: function (data) {
                    ChangeDescription(data);
                }
            });

        }
        else {
            ChangeDescriptionLocal(data.desc, data.a);
        }
        $('#videoThumbs').removeClass("active");
        $('#photoThumbs').addClass("active");

    }

    function bindEvents() {
        self.jqConsole.find(".images .previous").click(function () {
            if (self.curImg > 0) {
                self.curImg = self.curImg - 1;
                bindImageTmpl($(self.jqConsole.find(".images ul li").get(self.curImg)));
                updateImgCounter(self.curImg + 1);
                shiftThumbnails(self.imagesThumbnails, 1, false, true);
            }
        });

        self.jqConsole.find(".images .next").click(function () {
            if (self.curImg < self.imgN - 1) {
                self.curImg = self.curImg + 1;
                bindImageTmpl($(self.jqConsole.find(".images ul li").get(self.curImg)));
                updateImgCounter(self.curImg + 1);
                shiftThumbnails(self.imagesThumbnails, 1, true, true);
            }
        });
        self.jqConsole.find(".videos .previous").click(function () {
            if (self.curVid > 0) {
                self.curVid = self.curVid - 1;
                bindVideoTmpl($(self.jqConsole.find(".videos ul li").get(self.curVid)));
                updateVidCounter(self.curVid + 1);
                shiftThumbnails(self.videoThumbnails, 1, false, false);
            }
        });

        self.jqConsole.find(".videos .next").click(function () {
            if (self.curVid < self.vidN - 1) {
                self.curVid = self.curVid + 1;
                bindVideoTmpl($(self.jqConsole.find(".videos ul li").get(self.curVid)));
                updateVidCounter(self.curVid + 1);
                shiftThumbnails(self.videoThumbnails, 1, true, false);
            }
        });

        self.jqConsole.find(".images ul li").click(function () {
            var a = $(this),
            parA = a.parent(),
            counter = "",
            selectedIdx = 0,
            shift = 0,
            forward = false;
            if (parA) {
                selectedIdx = $(this).parent().find("li").index(this);
                counter = (selectedIdx + 1).toString();
            }
            bindImageTmpl(a);
            updateImgCounter(counter);
            shift = self.curImg - selectedIdx;
            forward = shift < 0 ? true : false;
            shiftThumbnails(self.imagesThumbnails, Math.abs(shift), forward, true);
            self.curImg = selectedIdx;
        });

        self.jqConsole.find(".videos ul li").click(function () {
            var a = $(this),
            parA = a.parent(),
            num = "",
            sum = 0;
            if (parA) {
                num = ($(this).parent().find("li").index(this) + 1).toString();
                sum = $(this).parent().find("li").length;
            }

            bindVideoTmpl(a);
            updateVidCounter(num);


        });

    }


    function preloadImages() {
        self.imagesThumbnails.find("li a").each(function () {
            var rel = $(this).attr("rel"),
                d2 = dataFromRel(rel),
                preLoader = new Image();
            preLoader.src = d2.url;
        });
    }

    function initializeConsole() {
        switch (sizeType) {
            case 1:
                self.thumbThreshold = 1;
                break;
            case 2:
                self.thumbThreshold = 2;
                break;
            case 3:
                self.thumbThreshold = 3;
                break;
        }
        self.shift = self.thumbThreshold * 58;
        self.jqConsole.find(".images ul").animate({ left: "+=" + self.shift.toString() + "px" }, 400);

        bindEvents();
    }

    initializePreview = function () {
        var liVid = self.videoThumbnails.find("li"),
            liImg = self.imagesThumbnails.find("li");
        if (liImg && liImg.length > 0) {
            bindImageTmpl(liImg.first());
        }
        else if (liVid && liVid.length > 0) {
            bindVideoTmpl(liVid.first());
        }
    };

    function init() {

        self.id = id;
        self.jqPreview = $('#preview' + id);
        self.jqConsole = $('#console' + id);
        self.videoThumbnails = self.jqConsole.find(".videos ul");
        self.imagesThumbnails = self.jqConsole.find(".images ul");
        self.imgN = $('#console' + id).find(".images li").length;
        self.vidN = $('#console' + id).find(".videos li").length;
        self.curImg = 0;
        self.curVid = 0;
        self.thumbThreshold = 3;
        self.sizeType = sizeType;

        initializePreview();
        initializeConsole();
        preloadImages();
    }

    init();
};
