/*
* Core Mixaroo Library
*/

/*
* JSLint Configuration:
*/
/*global $, Typekit, document, console */

var 
    firstSearch = true,
    currentChannelId = '',
    term = '',
    currentProgrammeId = '',
    twitterId = '',
    granularity = "day",
    oauth_consumer_key = '',
    country = null;


var ua = navigator.userAgent;
var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);

var mx = (function () {

    return {
        // Configuration Values
        googleAnalyticsCode: 'UA-19534259-3',
        domain: 'boxfish.com',
        facebookApiKey: (location.href.indexOf('http://localhost') == -1) ? '215751421773481' : '289096747775838' /* local host app */,

        // Initialization Script
        init: function () {

            if ($.cookie)
                country = $.cookie('country');

            $.accordion.init($('.column.left'));

            // Focus 
            if (jQuery('.focus').size() > 0) {
                jQuery('.focus:last').focus();
            }

            // Initialize Ajax Helpers  
            if (mx.ajax !== undefined) {
                mx.ajax.init();
            }

            // Initialize Homepage Helpers 
            if (mx.home !== undefined) {
                mx.home.init();
            }

            // Initialize Twitter Widget Helpers 
            if (mx.twitter !== undefined) {
                mx.twitter.init();
            }

            // Initialize Social API Helpers
            if (mx.social !== undefined) {
                mx.social.init();
            }

            // Initialize Video Player API Helpers
            if (mx.player !== undefined) {
                mx.player.init();
            }

            // Initialize Transcript API Helpers
            if (mx.transcript !== undefined) {
                mx.transcript.init();
            }

            // Initialize Transcript API Helpers
            if (mx.advertising !== undefined) {
                mx.advertising.init();
            }

            // Initialize Transcript API Helpers
            if (mx.amobee !== undefined) {
                mx.amobee.init();
            }

            // Initialize Relevance 
            if (mx.relevance !== undefined) {
                mx.relevance.init();
            }

            // Initialize Analytics
            if (mx.analytics !== undefined) {
                mx.analytics.init();
            }

            return true;
        },

        log: function (text) {
            if (console !== undefined) {
                console.log(text);
            }
        },

        formatCurrency: function (number) {
            number = isNaN(number) || number === '' || number === null ? 0.00 : number;
            return parseFloat(number).toFixed(2);
        },


        getParameterByName: function (name) {
            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null)
                return "";
            else
                return decodeURIComponent(results[1].replace(/\+/g, " "));
        },

        getCurrentCredentials: function () {
            return this.credentials;
        },

        setCredentials: function (consumerKey, hashSecret) {
            this.credentials = { consumerKey: consumerKey, secretHash: hashSecret };
        }


    };
} ());

jQuery(document)
    .ready(function () {
        mx.init();
    })
    .click(function (e) {
        if ($.programDetail) $.programDetail.shrink();
    }); ;

$.modal = function () { };

$.modal.create = function (options) {
    $('#overlay-background, .modal').remove();

    var modal =
        '<div id="overlay-background"></div><div class="modal"><div class="content">{0}</div></div>'

    modal = $($.string.format(modal, options.text));

    $('body').prepend(modal);

    var 
        top = $(window).height() / 2 - $('.modal').height() / 2,
        left = $(window).width() / 2 - $('.modal').width() / 2;

    $('.modal').css({ left: parseInt(left), top: parseInt(top) });
};

// http://stackoverflow.com/questions/610406/javascript-printf-string-format
String.prototype.format = function () {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{' + i + '\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
};

// Array Clone
// http://my.opera.com/GreyWyvern/blog/show.dml/1725165
function cloneObject(source) {
    var newObj = (source instanceof Array) ? [] : {};
    for (var i in source) {
        if (i == 'clone') {
            continue;
        }
        if (source[i] && typeof source[i] == "object") {
            newObj[i] = cloneObject(source[i]);
        } else {
            newObj[i] = source[i];
        }
    }

    return newObj;
}

$.extend($.expr[':'], {
    'containsi': function (elem, i, match, array) {
        return (elem.textContent || elem.innerText || '').toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
    }
});

/*
* hooking up the resize for the window
*/
$(window).resize(function () {
    $(document).ready(function () {
        var 
            windowHeight = $(window).height(),
            headerheight = $('#header').height();

        if (
            location.href.toString().toLowerCase().indexOf("/#search/") != -1
            || location.href.toString().toLowerCase().indexOf("/#mostshared") != -1
            ) { // design fix
            $('.column.right').offset({ left: $('.column.middle').offset().left + 488 + 15 });
        } else {
            $('.column.right').offset({ left: $('.column.middle').offset().left + 488 + 15 });
        }
        $('.column.left').offset({ left: $('#main-content').offset().left + 15 });
    });
});

/*
* hooking up the scroll event to fix the right and left column
*/
$(window).scroll(function () {
    var windowsTop = $(window).scrollTop();

    if (windowsTop > 45 /* header height + margin */) {
        $('.column.right, .column.left, .complementary').css({ marginTop: "-70px" });
        $('.column.left .logo').show();
    } else {
        $('.column.right, .column.left, .complementary').css({ marginTop: 0 });
        $('.column.left .logo').hide();
    }
});

/*
* get the image url for te thumbnails
*/
var alreadyUserThumbs = new Array();

// @entries -----------------
// dateTime : date and time to get the thumbnail from
// channel : channel where where to look up for the thumb
// size : original, big, medium, small
var getThumbFromDate = function (dateTime, channel, size) {
    if (!dateTime) return '';

    /*
    * getting the thumbnail a date
    *
    * 2011-10-23 T 23:32:39.025-07:00 - date pattern
    *
    */

    var 
        date = dateTime.split('T')[0],
        time = dateTime.split('T')[1],
        channelId = channel ? channel : currentChannelId,
        orignalSufix = ".jpg",
        bigSufix = "_310x174.jpg",
        mediumSufix = "_81x46.jpg",
        smallSufix = "_63x36.jpg";

    // https://s3.amazonaws.com/media.boxfish.com/thumbnails/##_CHANNELID_##/##_DATE_##/##_HOUR_##/##_UTC_START_TIME_IN_20_SEC_INTERVALS_##

    var randomMin = Math.floor(Math.random() * 59);

    if (randomMin < 10) {
        randomMin = randomMin + 10;
    }

    // work around as well
    if (!firstSearch) {
        randomMin = time.split(':', 3)[1];
    }

    var imageSrc =
        "https://s3.amazonaws.com/media.boxfish.com/thumbnails/" +
        channelId + "/" +
        date.split('-')[0] /*year*/ + date.split('-')[1] /*month*/ + date.split('-')[2] /*day*/ + "/" +
        time.split(':', 3)[0] /*hour*/ + "/" +
        date.split('-')[0] /*year*/ + date.split('-')[1] /*month*/ + date.split('-')[2] /*day*/ + time.split(':', 3)[0] /*hour*/ + /*randomMin*/time.split(':', 3)[1] + "00";

    // add the prefix
    switch (size) {
        default:
        case "original":
            imageSrc += orignalSufix;
            break;
        case "big":
            imageSrc += bigSufix;
            break;
        case "medium":
            imageSrc += mediumSufix;
            break;
        case "small":
            imageSrc += smallSufix;
            break;
    }

    alreadyUserThumbs.push(imageSrc);

    return imageSrc;
};

/*
accordion effect
*/
$.accordion = function () { };

$.accordion.init = function (target) {
    var delay = 500;

    target.find('.accordion').one('click', function () {
        $.accordion.toogle($(this));
    });

    // hooking up the anchor click for iPad better performance 
    target.find('.accordion .switch-accordion').click(function (e) {
        e.preventDefault();

        $(this).parent().click();

        return false;
    });
};

$.accordion.toogle = function (target) {
    var delay = 500;

    var func = null;


    var animated = function () {
        target.one('click', function () {
            $.accordion.toogle(target);
        });
    };

    if (target.hasClass('selected')) {
        target.removeClass('selected');
        func = $.fn.slideUp;
    } else {
        target.addClass('selected');
        func = $.fn.slideDown;
    }

    var child = target.parent().find('#' + target.attr('data-related'));
    if (child.length > 0) {
        func.apply(child, [delay, 'linear', animated]);
    }
    else {
        animated();
    }

};

/*
granularity filter
*/

$('.mentions-filter').click(function (e) {
//    if ($(this).hasClass('selected')) return;

    $(this).parent().find('img').remove();

    $(this).parent().append('<img width="15" style="float: right;" src="/content/img/loading.gif" alt="loading" />');

    $('.mentions-filter').removeClass('selected');

    $(this).addClass("selected");

    granularity = $(this).attr('data-granularity');

    /* get the trend rank number */
    // IMPORTANT : take http://api.boxfish.com/v1 off and use rawUrl var
    $.getScript('http://api.boxfish.com/v1/trend/RankAndCount/' + granularity + '/' + term + '?callback=$.home.getTrendRankCallBack');
   
    e.preventDefault();
});

/*
Shared constructor type for all tools to keep them the same format mimicing jqueryUI.
*/
$.fn.toolConstructor = function (target, className, args) {
    //call return $.fn.toolConstructor(this, options)

    if ( !className || !className.name ) { return; }

    var lowerName = className.name.toLowerCase();

    var arg0 = args[0];

    var args, funcName;
    if (typeof arg0 === "string") {
        funcName = arg0;
        args = Array.prototype.slice.call(args);
        args.shift();
    }

    return target.each(function () {
        var obj = this[lowerName];
        if (typeof arg0 === "string") {
            if (obj) {
                var func = obj[funcName];
                if (func != null)
                    func.apply(obj, args);

            }
        }
        else {
            if (!obj)
                this[lowerName] = obj = new className(this, arg0);
            else
                obj.setOptions(arg0);
        }

        return obj;
    });
};


