﻿
if (typeof console == "undefined" || typeof console.log == "undefined")
	var console = { log: function() { } };

var _isLoading = false;

jQuery.query = function(s) {
	var r = {};
	if (s) {
		var q = s.substring(s.indexOf('?') + 1); // remove everything up to the ?
		q = q.replace(/\&$/, ''); // remove the trailing &
		jQuery.each(q.split('&'), function() {
			var splitted = this.split('=');
			var key = splitted[0];
			var val = splitted[1];

			// convert numbers
			if (/^[0-9.]+$/.test(val))
				val = parseFloat(val);
			// convert booleans
			if (val == 'true')
				val = true;
			if (val == 'false')
				val = false;
			// ignore empty values
			if (val && (typeof val == 'number' || typeof val == 'boolean' || val.length > 0)) r[key] = val;
		});
	}
	return r;
};

jQuery.extend({
	utils: {
		decodeHTML: function(str) {
			return str.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
		},
		encodeHTML: function(str) {
			return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
		}
	}
});

groupy.fbQueries = function () {
	var d = document.location.toString();
	var q = (d.indexOf('?') > -1) ? d.substring(d.indexOf('?') + 1) : d;
	var r = '';

	jQuery.each(q.split('&'), function() {
		var splitted = this.split('=');
		var key = splitted[0];
		var val = splitted[1];

		if (key.length > 3 && key.substring(0, 3) == "fb_") {
			r += key + "=" + val + "&";
		}
	});

	return r;
}

groupy.changeLocation = function (url) {

	if ((url.indexOf('?') == -1)) {
		url += "?";
	} else {
		if (url.substring(url.length - 1) != "&") {
			url += "&";
		}
	}

	url += groupy.fbQueries();

	window.location = url;
}

groupy.trackOpen = function( url ) {

    //TODO: Implement tracking here, to know how many (and by who) sponsors links opened
    
    //window.open(url, 'name','attributes');
    window.open(url, '_wnlaPopup');
}

groupy.publishStory = function(userMessage, attachment, actionLinks, targetId, userMessagePromt, callback, autoPublish, actorId) {
    FB.ensureInit(function() {
        FB.Connect.requireSession(function() {
            FB.Connect.streamPublish(userMessage, eval(attachment), eval(actionLinks), targetId, userMessagePromt, callback, autoPublish, actorId);
        });
    });
}

groupy.parseFbml = function() {
	if (FB.XFBML.Host.parseDomTree) {
		setTimeout(FB.XFBML.Host.parseDomTree, 0);
	}
}

groupy.gup = 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 results[1];
}

/*
groupy.checkUtcOffset = function() {

	var d = new Date().getTimezoneOffset() / 60 * -1;

	//	keep cookie for two weeks from now
	var date = new Date();
	date.setTime(date.getTime() + (14 * 24 * 60 * 60 * 1000));

	var domain = null;
	var e = date.toGMTString();
	var p = "/";

	document.cookie = "utcOffset=" + escape(d)
				+ ((e) ? "; expires=" + e : "")
				+ ((p) ? "; path=" + escape(p) : "")
				+ ((domain) ? "; domain=" + domain : "");
}
*/

groupy.authenticate = function () {

    FB.ensureInit(function () {
        FB.Connect.requireSession(function () {
            alert(2);
        });
    });
}

groupy.reloadCurent = function() {
	window.location.reload();
}

groupy.enableElement = function(elementId) {
	$(elementId).removeAttr("disabled")
		.removeClass("disabled");
}

groupy.disableElement = function(elementId) {
	$(elementId).attr("disabled", "disabled")
		.addClass("disabled");
}



groupy.fluffMe = function (i, l, s) {
    var o = i.toString();
    if (!s) {
        s = '0';
    }
    while (o.length < l) {
        o = s + o;
    }
    return o;
};




$(function() {
	//groupy.checkUtcOffset();
	//setTimeout(groupy.parseFbml, 1000);
});




/*
groupy.cookie = function(name, value, options) {
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
*/

groupy.showLoader = function(html) {
	_isLoading = true;
	if (!html) {
		html = '&nbsp;'
	}
	$('#ajaxLoader').html(html).show();
}

groupy.hideLoader = function() {
	_isLoading = false;
	$('#ajaxLoader').hide();
}





groupy.initSlider = function () {

    //Set Default State of each portfolio piece
    $(".paging").show();
    $(".paging a:first").addClass("active");

    //Get size of images, how many there are, then determin the size of the image reel.
    var imageWidth = $(".window").width();
    var imageSum = $(".image_reel img").size();
    var imageReelWidth = imageWidth * imageSum;

    //Adjust the image reel to its new size
    $(".image_reel").css({ 'width': imageReelWidth });

    //Paging + Slider Function
    rotate = function () {
        var triggerID = $active.attr("rel") - 1; //Get number of times to slide
        var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

        $(".paging a").removeClass('active'); //Remove all active class
        $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

        //Slider Animation
        $(".image_reel").animate({
            left: -image_reelPosition
        }, 500);

    };

    //Rotation + Timing Event
    rotateSwitch = function () {
        play = setInterval(function () { //Set timer - this will repeat itself every 3 seconds
            $active = $('.paging a.active').next();
            if ($active.length === 0) { //If paging reaches the end...
                $active = $('.paging a:first'); //go back to first
            }
            rotate(); //Trigger the paging and slider function
        }, 18000); //Timer speed in milliseconds 
    };

    rotateSwitch(); //Run function on start

    //On Hover
    $(".image_reel a").hover(function () {
        clearInterval(play); //Stop the rotation
    }, function () {
        rotateSwitch(); //Resume rotation
    });

    //On Click
    $(".paging a").click(function () {
        $active = $(this); //Activate the clicked paging
        //Reset Timer
        clearInterval(play); //Stop the rotation
        rotate(); //Trigger rotation immediately
        rotateSwitch(); // Resume rotation
        return false; //Prevent browser jump to link anchor
    });
}


groupy.clearSearchFilter = function () {
    $('#filterSearchText').val('');
    groupy.submitForm();
}

groupy.clearDealFilter = function () {
    $('#filterDealId').val('');
    groupy.submitForm();
}


groupy.goToPage = function (pageIndex) {
    $("#currentPage").val(pageIndex);
    $("#gridAction").val("CurrentPageChanged");
    groupy.submitForm();
}

groupy.onPageSizeChange = function (pageIndex) {
    $("#gridAction").val("PageSizeChanged");
    groupy.submitForm();
}

groupy.sort = function (sortField, sortDirection) {
    $("#gridAction").val("Sorted");
    $("#sortField").val(sortField);
    $("#sortDirection").val(sortDirection);
    groupy.submitForm();
}

groupy.submitForm = function() {
    $("form").submit();
}

groupy.goToPage = function (pageIndex) {
    $("#currentPage").val(pageIndex);
    $("#gridAction").val("CurrentPageChanged");
    groupy.submitForm();
}

groupy.onPageSizeChange = function (pageIndex) {
    $("#gridAction").val("PageSizeChanged");
    groupy.submitForm();
}

groupy.sort = function (sortField, sortDirection) {
    $("#gridAction").val("Sorted");
    $("#sortField").val(sortField);
    $("#sortDirection").val(sortDirection);
    groupy.submitForm();
}



jQuery.fn.equalCols = function () {
    //Array Sorter
    var sortNumber = function (a, b) { return b - a; };
    var heights = [];
    //Push each height into an array
    $(this).each(function () {
        heights.push($(this).height());
    });
    heights.sort(sortNumber);
    var maxHeight = heights[0];
    return this.each(function () {
        //Set each column to the max height
        $(this).css({ 'height': maxHeight });
    });
};


jQuery.fn.supersleight = function (settings) {
    settings = jQuery.extend({
        imgs: true,
        backgrounds: true,
        shim: '/images/x.gif',
        apply_positioning: true
    }, settings);

    return this.each(function () {
        if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
            jQuery(this).find('*').andSelf().each(function (i, obj) {
                var self = jQuery(obj);
                // background pngs
                if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
                    var bg = self.css('background-image');
                    var src = bg.substring(5, bg.length - 2);
                    var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
                    var styles = {
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
                        'background-image': 'url(' + settings.shim + ')'
                    };
                    self.css(styles);
                };
                // image elements
                if (settings.imgs && self.is('img[src$=png]')) {
                    var styles = {
                        'width': self.width() + 'px',
                        'height': self.height() + 'px',
                        'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
                    };
                    self.css(styles).attr('src', settings.shim);
                };
                // apply position to 'active' elements
                if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')) {
                    self.css('position', 'relative');
                };
            });
        };
    });
};
