﻿//Version 1.0.3

var IGA = IGA || {};

//Requires Jtemplates and Jquery

IGA.cleanText = function(html){
	return html.replace(/&amp;quot;/g,'"');
};

IGA.toArray = function(iterable) {
    if (!iterable) return [];
    if (iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
};

IGA.utils = function() {
    var that = {};

    //Make sure  title has no spaces
    that.openWindow = function(url, title) {
        var defaultConfig = {
            'width': '853',
            'height': '500',
            'status': 'no',
            'menubar': 'no',
            'toolbar': 'no',
            'resizable': 'no',
            'location': 'yes',
            'scrollbars': 'no',
            'directories': 'no'
        };
        return window.open(url, title, IGA.url.toQueryString(defaultConfig, ","));
    };

    return that;
} ();




IGA.utils.cookie = function() {
    var that = {};

    that.createCookie = function(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=/";
    };

    that.readCookie = function(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 null;
    };


    
    that.eraseCookie = function(name) {
        createCookie(name, "", -1);
    };
    return that;

} ();

/**
* Returns the keys (property names) of an object.
*/
IGA.keys = function(object) {
    var keys = [];
    for (var property in object)
        keys.push(property);
    return keys;
};

IGA.url = function() {
    var that = {};
    /** Fetches parmeters off of an url
    * @param paramName If null or undefined, all parameters will be returned as an object.  If specified as 
    * a string, returns the value of that parameter.
    * @param url If null or undefined, the current location.href is used.  If set, uses the specified url as
    * the source of the parameters.
    */
    that.params = function(paramName, url) {
        if (!url) {
            url = location.href;
        }
        var queryParams = url.split("?");
        if (queryParams.length > 1) {
            var paramsObj = that.fromQueryString(queryParams[1]);
            if (paramsObj && paramName)
                return paramsObj[paramName];
            return paramsObj;
        }
        if (paramName)
            return null;
        return {};
    };

    /**
    * Builds an url by passing an array of path parts and an object containing the
    * queryString parts as key/value pairs.
    */
    that.build = function(pathArr, qsObj) {
        var ps = "";

        var pathAdd = function(i, p) {
            p = p.toString();
            ps += p;
            if (!p.lastIndexOf("/") == p.length - 1 && i < pathArr.length - 1) {
                ps += "/";
            }
        };
        if (pathArr) {
            jQuery.each(pathArr, pathAdd);
        }
        return that.addParams(qsObj || {}, ps);
    };

    /***
    * Adds a single key value pair to a url making certain to use the correct query parameter separation and encoding.
    */
    that.addParam = function(k, v, url) {
        var o = {};
        o[k] = v;
        return that.addParams(o, url);
    };

    that.addParams = function(params, url) {
        url = url || location.href;
        var h = that.getHash(url, true);
        var parts = url.split("#");
        url = parts[0];
        var qs = that.toQueryString(params);
        url = that._stripXtra(url);
        var i = url.indexOf("?");
        if (i == -1)
            url += "?";
        else
            qs = "&" + qs;
        return url + qs + h;
    };

    /**
    * Gets the hash part of the url or empty string if none exists.
    */
    that.getHash = function(url, inc) {
        url = url || location.href;
        var parts = url.split("#");
        if (parts.length > 1) {
            return inc ? "#" + parts[1] : parts[1];
        }
        return "";
    };

    that.removeHash = function(url) {
        url = url || location.href;
        return url.split("#")[0];
    };

    /**
    * Removes one or more parameters from an url and returns the url.
    */
    that.removeParam = function(names, url) {
        url = url || location.href;
        var front = url.split("?")[0];
        var params = that.params(null, url);
        names = jQuery.isArray(names) ? names : [names];
        jQuery.each(names, function(i, name) {
            delete params[name];
        });
        var res = that.addParams(params, front + that.getHash(url, true));
        return that._stripXtra(res);
    };

    that._stripXtra = function(url) {
        if (!url)
            return url;
        var lst = url.charAt(url.length - 1);
        if (lst == "?" || lst == "&")
            url = url.substr(0, url.length - 1);
        return url;
    };

    /**
    * Turns a queryString into a object of key/value pairs.
    * If a key is specified more than once, the resulting value will be an array
    * containing all values for that key.
    */
    that.fromQueryString = function(str) {
        var obj = {};
        jQuery.each(str.split("&"), function(i, pair) {
            var parts = pair.split("=");
            var key = parts[0];
            if (parts.length == 2) {
                var val = that.decUri(parts[1]);
                var oldVal = obj[key];
                if (oldVal) {
                    if (!jQuery.isArray(oldVal)) {
                        obj[key] = [oldVal];
                    }
                    obj[key].push(val);
                }
                else {
                    obj[key] = val;
                }
            }
        });
        return obj;
    };
    /**
    * A version of decodeURIComponent that decodes + as space (as per the RFC).
    * 
    */
    that.decUri = function(str) {
        return decodeURIComponent(str).replace(/\+/g, " ");
    };

    that.friendly = function(str) {
        return str.toLowerCase() // change everything to lowercase
				.replace(/[_|\s]+/g, "-") // change all spaces and underscores to a hyphen
				.replace(/[^a-z0-9-]+/g, "") // remove all non-alphanumeric characters except the hyphen
				.replace(/[-]+/g, "-"); // replace multiple instances of the hyphen with a single instance
    };

    /**
    * Turns an object of key value pairs into a string.
    * If a value is an array it will be turned into multiple
    * of the same key with different values.
    */
    that.toQueryString = function(obj, separator) {
        if (!separator)
            separator = "&";

        var parts = [];
        var keys = IGA.keys(obj);
        /**
        * @ignore
        */
        var addFx = function(key, val) {
            parts.push(key + "=" + encodeURIComponent(val));
        };

        jQuery.each(keys, function(i, key) {
            var val = obj[key];

            if (jQuery.isArray(val))
                jQuery.each(val, function(i, v) { addFx(key, v); });
            else
                addFx(key, val);
        });
        return parts.join(separator);
    };
    return that;
} ();


IGA.keys = function(object) {
	var keys = [];
	for (var property in object)
		keys.push(property);
	return keys;
};

IGA.twitter = function() {
    var that = {};

    var refreshRate = 30000;

    that.setRefreshRate = function(newRate) {
        refreshRate = newRate;
    };

    that.setTemplateUrl = function(target, templateName) {
        $(target).setTemplateURL(templateName);
        that.target = target;
    };
    that.setTemplate = function(target, template) {
        $(target).setTemplate(template);
        that.target = target;
    };

    that.getFriendsStatuses = function(userName) {
        var urladdress = "http://twitter.com/statuses/friends.json?screen_name=" + userName;
        $.ajax({

            type: "GET",
            url: urladdress,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            cache: false,
            success: function(msg) {

                // Sort by time
                msg.sort(function(b, a) {
                    if (a.status.created_at == b.status.created_at) { return 0; }
                    return Date.parse(IGA.twitterDateFix(a.status.created_at)) - Date.parse(IGA.twitterDateFix(b.status.created_at));
                });

                // Render the resulting data, via template.
                that.processTemplate(msg);
                setTimeout(function() { that.getFriendsStatuses(userName); }, 30000);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest);
            }
        });
    };

    that.getFollowerCount = function(userName, callbackFx) {
        var urladdress = "http://twitter.com/users/show.json?screen_name=" + userName;
        $.ajax({
            type: "GET",
            url: urladdress,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            cache: false,
            success: function(msg) {
                // Render the resulting data, via template.
                callbackFx(msg.followers_count);

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest);
            }
        });
    };

    that.getLatestTweets = function(searchQuery, resultPerPage) {
        var urladdress = "http://search.twitter.com/search.json?q=" + searchQuery + "&rpp=" + resultPerPage;
        $.ajax({
            type: "GET",
            url: urladdress,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            cache: false,
            success: function(msg) {
                // Render the resulting data, via template.
                that.processTemplate(msg);
                setTimeout(function() { that.getLatestTweets(searchQuery, resultPerPage); }, refreshRate);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest);
            }
        });
    };




    that.getArtistTweets = function(userName, count) {
        var urladdress = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" + userName + "&count=" + count + "&include_rts=1";
        $.ajax({
            type: "GET",
            url: urladdress,
            contentType: "application/json; charset=utf-8",
            dataType: "jsonp",
            cache: false,
            success: function(msg) {
                // Render the resulting data, via template.
                that.processTemplate(msg);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest);
            }
        });
    };

    that.processTemplate = function(data) {
        $(that.target).processTemplate(data);
    };


    that.closeNotify = function() {
        $('#notify-table').fadeOut('slow');
        IGA.utils.cookie.createCookie("50cent_notify", "false", 1);
    };

    return that;

};

IGA.tweetTo = function() {
    var that = {};
    that.window = {};
    that.events = [];

    that.sendTweet = function(url, params, title) {
        var url = IGA.url.addParams(params, url);
        that.window = IGA.utils.openWindow(url, title);
    };

    that.showNotify = function() {
        $('#notify-table').slideDown('slow');
    };

    that.onComplete = function(listenerFx) {
    that.events.push({ fx: listenerFx });
    };

    that.msgPosted = function(username, profile_img, tweet) {
        var args = IGA.toArray(arguments);
        jQuery.each(that.events, function(i, evt) {
            evt.fx.apply(null, args);
        });
    };

    that.getTweetCount = function(campaignId) {

    };

    return that;
} ();

jQuery.fn.IGATweetSharePermalink = function(url, tweet) {

    var that = {};
    that.apiurl = "http://sdk.artist.gffn.com/TwitterShareAsyncRx.ashx";


    $(this).click(function(evt) {
        evt.preventDefault();
        IGA.tweetTo.sendTweet(that.apiurl, {
            tweet: encodeURIComponent(tweet),
            utm_term: IGA.url.params("utm_term"),
            url: encodeURIComponent(url)
        }, 'TweetShare');
    });
};



jQuery.fn.IGATweetShare = function(text, campaignId) {

    var that = {};
    that.apiurl = "http://dev.apps.interscope.com/webservices/TwitterShare.ashx";


    $(this).click(function() {
        that.tweet = $(text).val();
        IGA.tweetTo.sendTweet(that.apiurl, {
            tweet: encodeURIComponent(that.tweet),
            campaignId: campaignId,
            utm_term: IGA.url.params("utm_term")
        }, 'TweetShare');
        if(pageTracker)
            pageTracker._trackPageview('/outgoing/twittershare/' + campaignId);
    });
};

jQuery.fn.IGATweetCount = function(campaignId) {

    var that = {};
    that.selector = this;

    $.ajax({
        url: "http://dev.apps.interscope.com/webservices/TweetShareCount.asmx/GetCampaignCount?campaignId=" + campaignId,
        dataType: "jsonp",
        jsonpCallback: "iga_tweet_share",
        success: function(response) {
            var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var result = parseInt(data[0].Count, 10);
            if (result > 10000) {
                result = Math.round(result / 1000) + "K";
            }
            $(that.selector).html(result);
        },
        failure: function(msg) {
            alert(msg);
        }
    });

};

jQuery.fn.IGATweetCountPermalink = function(url) {

    var that = {};
    that.selector = this;

    $.ajax({
        url: "http://sdk.artist.gffn.com/TweetShare.asmx/GetPermalinkStats?url='" + encodeURI(url) + "'",
        dataType: "jsonp",
        jsonpCallback: "iga_tweet_share",
        success: function(response) {
            var data = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
            var result = parseInt(data.TweetCount, 10);
            if (result > 10000) {
                result = Math.round(result / 1000) + "K";
            }
            else if (result !== 0) {
                $(that.selector).html(result);
            }
        },
        failure: function(msg) {
            alert(msg);
        }
    });

};

IGA.twitterRelativeTime = function(time_value) {
    //Date format differences
    //Tue, 19 Jan 2010 20:33:58 +0000
    var correctDate = /^\D{3},\s\d{1,2}\s\D{3}\s\d{2,4}\s\d{2}:\d{2}:\d{2}\s\+0000$/i;
    //Wed Sep 09 23:07:49 +0000 2009
    var modifiedDate = /^\D{3}\s\D{3}\s\d{2,4}\s\d{2}:\d{2}:\d{2}\s\+0000\s\d{2,4}$/i;

    var parsed_date = "";

    if (correctDate.test(time_value))
        parsed_date = Date.parse(time_value);
    else if (modifiedDate.test(time_value))
        parsed_date = Date.parse(IGA.twitterDateFix(time_value));

    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    if (delta < 60) {
        return 'less than a minute ago';
    } else if (delta < 120) {
        return 'about a minute ago';
    } else if (delta < (45 * 60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if (delta < (90 * 60)) {
        return 'about an hour ago';
    } else if (delta < (24 * 60 * 60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if (delta < (48 * 60 * 60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
};

//		time_value	"Tue, 19 Jan 2010 20:33:58 +0000"	String
//Fix: IE would not parse "Wed Sep 09 23:07:49 +0000 2009" and FF would not parse without "2009" at the end 
IGA.twitterDateFix = function (twitter_time) {
	var baddate=twitter_time.split(" ");
	return newdate=baddate[0]+" "+baddate[1]+" "+baddate[2]+" "+baddate[5]+" "+baddate[3]+" "+baddate[4];
};


jQuery.fn.twitterCounter = function(options) {
    var curSize = $(this).val().length;
    var charsLeft = options['limit'] - curSize;
    var types = ['ok', 'watch', 'warning', 'error'];
    var x = {};
    $.each(types, function() {
        var el = this.toString();
        x[el] = { 'Max': options[el + 'Size'],
            'Style': options[el + 'Style'].substring(0, 1) == '.' || options[el + 'Style'].substring(0, 1) == '#' ? options[el + 'Style'].substring(1, options[el + 'Style'].length) : options[el + 'Style'],
            'Type': options[el + 'Style'].substring(0, 1) == '.' ? 'class' : 'id'
        }
    });
    for (var i = 0; i < types.length; i++) {
        var el = types[i].toString();
        // Last Element check
        if (i + 1 < types.length) {
            var nextEl = types[i + 1].toString();
            // console.debug(charsLeft, el, x[el]['Max'], x[nextEl]['Max']+1, charsLeft > x[nextEl]['Max'] && charsLeft < x[el]['Max'] + 1);
            if (charsLeft > x[nextEl]['Max'] && charsLeft < x[el]['Max'] + 1) {
                clean();
            }
        } else {
            // console.debug(charsLeft, el, x[el]['Max'], x[nextEl]['Max']+1, charsLeft < x[el]['Max'] + 1);
            if (charsLeft < x[el]['Max']) {
                clean();
            }
        }
    }

    $(options['counter']).text(charsLeft);
    // Add an event so the counter updates when the user types.
    $(this).one('keyup', function() {
        $(this).twitterCounter(options);
    });
    function clean() {
        if (x[el]['Type'] == 'class') {
            $.each(types, function() {
                var temp = this.toString();
                if ($(options['counter']).hasClass(temp)) {
                    $(options['counter']).removeClass(temp);
                }
            });
            $(options['counter']).addClass(x[el]['Style']);
        } else {
            $(options['counter']).id(x[el]['Style']);
        }
    }
};


var twittershares = $('.tweet_share');

var loadTwitterShareButtons = function() {

    if (twittershares.length > 0) {
        twittershares.each(function() {
            var shareUrl = $(this).attr('share_url');
            var tweet = $(this).attr('tweet');
            var prepend = $(this).attr('prepend');
            if (!shareUrl)
                shareUrl = location.href;

            $(this).IGATweetSharePermalink(shareUrl, prepend + " " + tweet);

            $(this).html('<span class="tweet_share_small" style="float:left"><img class="tweet_share_button_image" style="border:none" src="http://dev2.ladygaga.interscope.com/_shared/images/twitter_share.png" /></span> \
            <span class="tweet_share_count" style="font-family:lucida grande,tahoma,verdana,arial,sans-serif; height:16px; float:left; font-size:14px; margin-top: 1px"><span class="tweet_share_count_inner" style="padding:2px 6px 3px"></span></span>');
        });
    }
};

//If twitter share links present load counts and buttons
$(function() {
    if (twittershares.length > 0) {
        twittershares.each(function() {
            var shareUrl = $(this).attr('share_url');
            if (!shareUrl)
                shareUrl = location.href;

            var countElem = $(this).find('.tweet_share_count_inner');
            countElem.IGATweetCountPermalink(shareUrl);

        });
    }
});

loadTwitterShareButtons();
