﻿var flowli = {}

flowli.collapsed_expanded = function(){
	$(".collapsed,.expanded").live("click", function () {
		$(this).toggleClass("collapsed").toggleClass("expanded");
		$(this).nextAll(".toggle:first").slideToggle("normal");
		return false;
	});

	// collapse after page load
	$(".collapsed").each(function(){
		$(this).nextAll(".toggle:first").hide();
	});
	
	// open text by url#textid
	var open_it_ui = $(window.location.hash)

	if (open_it_ui.present())
		if (open_it_ui.hasClass("collapsed"))
			open_it_ui.click();
};

flowli.form_validation = function(){
	$("form").each(function (i, item) {
		$(item).validate({ errorPlacement: function (error, element) { } });
	});
};

flowli.activator = function () {
	var decoded_uri = decodeURI(window.location.pathname).toLowerCase().split('/');
	$("ul.activate").each(function (i, ul) {

		var url_elements = [];

		$(ul).find("li").each(function (i, li) {
			var envelope = $(li).data("activate");
			if (envelope !== undefined) {

				var url = {
					"url": envelope || "______________",
					"count": $.inArray(envelope.toString().toLowerCase(), decoded_uri),
					"li": $(li)
				};

				url_elements.push(url);
			};
		});

		var poped = url_elements.sort(function (first, second) { return first.count - second.count; }).pop();

		if (poped.count > 0) { poped.li.addClass("active"); };

	});
};
flowli.show_more_xhrs = [];
flowli.show_more_previous = [];

flowli.show_more = function (id, parameter, refresh) {

    // try define take by .show_more_top, if no try by li
    var take = $("section#" + id).closest("section").find(".show_more_item").size();
    if (take < 1) { take = $("section#" + id).closest("section").find("li").size(); }

    var skip = take;

    $("section#" + id + " .more").unbind();
    if (refresh) {
        skip = 0;
        $("section#" + id).closest("section").find("li").each(function (i, e) {
            flowli.show_more_previous.push(e);
            $(e).remove();
        });

    };

    if (typeof jQuery.sharerender != "undefined") {  $("#" + id + " ul li").find(".jquery-sharerender").each(function (o, item) { $(item).sharerender(); }); };

    $("section#" + id + " .more").click(function (e) {
        var link = $(this);
        var original_text = link.html();

        link.html("Loading..");

        var request = $.ajax({ url: "/get/" + id + "?parameter=" + parameter + "&take=" + take + "&skip=" + skip, success: function (data) {

            var new_items = $(data).find(".show_more_item");
            if (new_items.size() < 1) { new_items = $(data).find("li"); }

            var list_ui = $("#" + id + " .show_more_list");
            if (list_ui.size() < 1) { list_ui = $("#" + id + " ul"); }

            new_items.each(function (i, item) {
                list_ui.append(item);
            });
            if (new_items.length < 1 && refresh) {
                flowli.show_more_previous.forEach(function (item) {
                    list_ui.append(item);
                });
            };
            if (new_items.length > 1) {
                flowli.show_more_previous = [];
            };

            skip += take;
            link.html(original_text);

            //if ($.isFunction($.fn.tabs)) { jQuery(".tabs").tabs(); };
            if (typeof prettyDate != "undefined") { jQuery("time.human").prettyDate(); };
            if (typeof page != "undefined" && typeof page.on_resize != "undefined") { page.on_resize(); };
            if (typeof jQuery.sharerender != "undefined") { list_ui.find(".jquery-sharerender").sharerender(); };
        }
        });
        if (refresh) {
            flowli.show_more_xhrs.push(request);
        };
        return false;
    });

    if (refresh) { $("section#" + id + " .more").click(); };
};

window.log = function(obj) {
	if (window.console) {
		return window.console.log(obj);
	}
};
// usage
// var x = 42;
// var map = function (x) { return eval(x); };
// alert(f("x $x", map));
window.f = function (s, map) {
	return s.replace(/\$(\w+)/g, function (dummy, v) { return map(v);} );
};

window.flowli = flowli;

jQuery.fn.ids = function() {
	var ids;
	ids = this.map(function() {
		return $(this).attr("data-id");
	});
	return $.unique(ids.get());
};
jQuery.fn.blank = function() {
  return this.size() === 0;
};
jQuery.fn.present = function() {
  return this.size() > 0;
};

 (function ($) {
	$.queryString = (function (a) {
		if (a == "") return {};
		var b = {};
		for (var i = 0; i < a.length; ++i) {
			var p = a[i].split('=');
			if (p.length != 2) continue;
			b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
		}
		return b;
	})(window.location.search.substr(1).split('&'))
 })(jQuery);

$(function () {
	flowli.collapsed_expanded();
	
	// msa Call function if plugin here
	if ($.isFunction($.fn.validate)) flowli.form_validation();
	if ($.isFunction($.fn.placeholder)) $("textarea, input").placeholder();
	if ($.isFunction($.fn.smoothScroll)) $(".smoothscroll a").smoothScroll();
	
	flowli.activator();
});

/** * jQuery Cookie plugin * * Copyright (c) 2010 Klaus Hartl (stilbuero.de) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */
//github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

