/* General Namespace */

/* add focus pseudo-class if not already defined (jQuery v1.6+) */
if (!('focus' in jQuery.expr[':'])) {
    jQuery.expr[':'].focus = function( elem ) {
        return elem === document.activeElement && ( elem.type || elem.href );
    };
}

var InterNations = {};



/* General Initialization */

InterNations.init = function () {
    /* Trigger Buttons Highlight  */

    jQuery(".triggerbutton, .triggerbutton-submit").highlightClass("triggerbutton-highlight");
    jQuery(".triggerbutton3, .triggerbutton-submit3").highlightClass("triggerbutton-highlight3");
    jQuery(".triggerbutton-big").highlightClass("triggerbutton-big-highlight");


    /* Embed labels and titles into form fields */
    jQuery('[type=text], textarea').not(':focus').embeddedLabels();


    /* Dropdown Navigation */

    jQuery(".dropdown-navigation select").dropdownNavigation();


    /* Radio Navigation */

    jQuery(".radio-navigation, .radio-tab-navigation").radioNavigation();


    /* Tab Navigation */

    jQuery(".tab-navigation.ajax-navigation a").click(function (e) {
            var aEl = jQuery(this),
                    href = aEl.attr("href"),
                    navEl = aEl.parent(),
                    tabEl = jQuery(href);

            navEl.add(tabEl).addClass("active").siblings().removeClass("active").removeClass("last-active");

            if (navEl.hasClass("last")) {
                    navEl.addClass("last-active");
            }

            /* Teaser with two or three tabs (Startpage) */

            var container = navEl.parents(".teaser-tabbed").eq(0);
            if (container.length > 0) {
                    var number = href.substr(href.length - 1, 1);
                    for (var i = 1; i <= 3; i++) {
                            container.removeClass("tab-active-" + i);
                    }
                    /* Set class with the number of the active tab */
                    container.addClass("tab-active-" + number);
            }

            e.preventDefault();
    });


    /* Show search options when search field is focussed */

    jQuery(".list-search :text").focus(function () {
            var searchOptions = jQuery(this).parents("form").find(".search-options");
            searchOptions.show().find(".hide").unbind("click").click(function () {
                    searchOptions.hide();
            });
    });


    /* Section Toggle */

    jQuery(".section-toggle .section-switch").click(function (e) {
            jQuery(this).toggleClass("section-switch-visible")
                    .parents(".section-toggle").eq(0).find(".section-body").toggleClass("section-body-visible");
    });


    /* Profile: Grant Privacy Rights */

    jQuery(".grant-rights .section-heading input").click(function (e) {
            jQuery(this).parents(".section-toggle").eq(0).find(".section-body input").each(function() {
                    this.checked = !this.checked;
            });
    });

    jQuery("[data-segvar]").click(function(evt) {
        InterNations.trackSegVar(
            jQuery(evt.target).attr('data-segvar')  || jQuery(evt.currentTarget).attr('data-segvar'),
            jQuery(evt.target).attr('data-segment') || jQuery(evt.currentTarget).attr('data-segment')
        );
    });

    $('textarea[maxlength]').keyup(function() {
        if ($(this).val().length > $(this).attr('maxlength')) {
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }
    });

    $('form').submit(function() {
        $('textarea.trim').each(function() {
            $(this).val($.trim($(this).val()));
        });
    });
};

/* Register Initialization Handler */
$(InterNations.init);

/* General Sharing Form */
/* (Photo / Album Sharing, IN Invitation, Group Recommendation, Forum Thread Recommendation etc.) */

InterNations.SharingForm = {

	init : function (search_params) {

		/* Setup search */
		this.search_params = search_params || {};
		var search_form = jQuery('#search_people_form');
		this.search_action = search_form.attr("action");

		/* Setup event handlers */

		search_form.submit(this.searchPeople);

		/* Disable submit button when clicked */
		jQuery('#apply_share_form').submit(function () {
			jQuery(this).find(':submit').attr("disabled", true);
		});

		/* Show Ajax loading animation */
		jQuery('#search_people_loader').bind('ajaxStart', function() {
			jQuery(this).show();
		}).bind("ajaxComplete", function(){
			jQuery(this).hide();
		});

	},

	searchPeople : function (e) {
		e.preventDefault();
		var self = InterNations.SharingForm;

		var search_string = jQuery.trim(jQuery('#search_people').val());

		if (search_string == '') {
                    alert('Please enter a search string');
                    return;
		}

		var params = {
                    q: jQuery('#search_people').val(),
                    contactsOnly: 0
		};

		var search_params = self.search_params;
		if (search_params.id_parameter_name &&  search_params.id) {
			params[search_params.id_parameter_name] = search_params.id;
		}

                jQuery('#search_people_results').html('');

                jQuery.getJSON(self.search_action + '?' + jQuery.param(params), function(response) {
                    if (!response.success) {
                        jQuery('#search_people_results').html('An error occured, please try again later');
                        return;
                    }

                    if (response.resultCount == 0) {
                        jQuery('#search_people_results').html('Your search did not return any results');
                        return;
                    }

                    jQuery('#search_people_results').html(response.content);
                });
	},

	addPerson : function (user_id) {

		/* Hide & Append */
		var listItem = jQuery("#invite_" + user_id).hide();
		jQuery('#shared_contacts').append(
			'<li id="invited_' + user_id + '"' +
			' onclick="InterNations.SharingForm.removePerson(' + user_id + ')"' +
			' unselectable="on"' +
			' title="Remove from list">' +
				listItem.text() +
			'</li>'
		);
		jQuery('#invited_' + user_id).effect("highlight", {}, 500);

		jQuery('#apply_share_form :submit').attr("disabled", false);
		jQuery('#shared_with_nobody').hide();

		/* Update hidden field with IDs */
		var ids_field = jQuery('#share_people_ids');
		if(ids_field.val() == '') {
			ids_field.val(user_id);
		} else {
			ids_field.val(ids_field.val() + ',' + user_id);
		}
	},

	removePerson : function (user_id) {
		jQuery("#invited_" + user_id).remove();
		jQuery('#invite_' + user_id).show();

		/* Update hidden field with IDs */
		var ids_field = jQuery('#share_people_ids');
		var ids = ids_field.val().split(/,/);
		for (var i = 0; i < ids.length; i++) {
			if (ids[i] == user_id) {
				ids.splice(i, 1);
				break;
			}
		}
		ids_field.val(ids.join(','));

		if (ids.length == 0) {
			jQuery('#apply_share_form :submit').attr("disabled", true);
			jQuery('#shared_with_nobody').show();
		}
	}
};


/* Flash Messages */

InterNations.flash = function (message, caption) {
	jQuery('.flash h3').html(caption);
	jQuery('.flash p').html(message);
	jQuery('.flash').show();
};

InterNations.trackSegVar = function(segVar, segment, preservePreviousVar) {
    segment = segment || 1;
    _gaq.push(function() {
        var tracker = _gat._getTrackerByName();

        if (tracker._getVisitorCustomVar(1) && !preservePreviousVar) {
//            console.debug('Delete custom var');
            tracker._deleteCustomVar(1);
        }

        if (segVar) {
//            console.debug('Set custom var ' + segVar + '=' + segment + ' scope: ' + 1);
            tracker._setCustomVar(1, segVar, segment, 1);
            tracker._trackPageview();
        }
    });
};

/* Powerlayer Helpers */

InterNations.Powerlayers = {
	modalThickbox : function (uri, width, segVar, segment) {
            if (segVar) {
                InterNations.trackSegVar(segVar, segment);
            }

            tb_show(null, uri + (uri.indexOf('?') != -1 ? '&' : '?') + 'modal=true&width=' + width, false);
            jQuery(window).scrollTop(0);
	},
	postThread : function (uri) {
            this.modalThickbox(uri, 490);
	},
	groupTopic : function (uri) {
            this.modalThickbox(uri, 550);
	},
	joinGroup : function (uri) {
            this.modalThickbox(uri, 550);
	},
	joinActivityGroup : function (uri, id) {
            var segVar = 'ut:activityGroups/layer/' + id;
            this.modalThickbox(uri, 550, segVar);
	},
	inviteToGroup : function (uri) {
            this.modalThickbox(uri, 550);
	},
	eventGuestList : function (uri) {
            this.modalThickbox(uri, 500);
	},
	eventUpgrade : function (uri) {
            var segVar, segment;

            var re = /\/events\/(albatross_only|ticketshop|upgrade)_dialog\/(\d+)/;
            if (re.test(uri)) {
                segVar = 'ut:event/layer';
                segment = uri.replace(re, '$2');
            }

            this.modalThickbox(uri, 480, segVar, segment);
	},
	messageLimit : function (uri) {
            this.modalThickbox(uri, 430);
	},
	contactLimit : function (uri) {
            this.modalThickbox(uri, 460);
	},
        upgrade : function (uri) {
            var segVar;
            if (/magazine$/.test(uri)) {
                segVar = 'ut:content/layer/magazine';
            } else if (/guide$/.test(uri)) {
                segVar = 'ut:content/layer/cc-guide';
            }

            this.modalThickbox(uri, 500, segVar);
        },
	albatrossBenefits : function (uri) {
            var segVar;
            if (/\?messages$/.test(uri)) {
                segVar = 'ut:message/layer';
            } else if (/\?groups$/.test(uri)) {
                segVar = 'ut:group/layer';
            } else if (/\?magic_cap$/.test(uri)) {
                segVar = 'ut:magic_cap/layer';
            }

            this.modalThickbox(uri, 700, segVar);
	},
	emailImporter : function (uri) {
            this.modalThickbox(uri, 450);
	},
	become_member : function(uri) {
            this.modalThickbox(uri, 620);
        },
        members_only : function(uri) {
            this.modalThickbox(uri, 460);
        },
        eventNameTags : function(uri) {
            this.modalThickbox(uri, 550);
	}
};


/* Shows the Skype Box */

InterNations.SkypeBox = {
	current_id : null,
	show : function (user_id) {
		var new_id = "skype-box-" + user_id;
		if (new_id != InterNations.SkypeBox.current_id) {
			InterNations.SkypeBox.hide();
			ne_toggle_fade(new_id);
		}
		InterNations.SkypeBox.current_id = new_id;
	},
	hide : function () {
		var current_id = InterNations.SkypeBox.current_id;
		if (current_id != null) {
			ne_toggle_fade(current_id);
		}
		InterNations.SkypeBox.current_id = null;
	}
};


/* Twinkle Functions */

InterNations.Twinkle = {
	create : function (id, target,returned) {
		var url="/twinkle/create/" + id;
		if (returned) {
			url+='?returned=1';
		}
		jQuery.post(
			url,
			{},
			function (msg) {
				if (target) {
					var elem = jQuery("#" + target);
					elem.html(msg);
					if (elem.is("a")) {
						elem.removeAttr("href").attr("onclick", null).addClass("twinkle_sent").removeClass("action");
					}
				}
			}
		);
		return false;
	},
	hide : function (twinkle_id, notif_id) {
		jQuery.post(
			'/twinkle/hide/' + twinkle_id + '?del_notifeed=' + notif_id,
			{},
			function () {
				jQuery("#notif_row_"+notif_id).hide();
			}
		);
	}
};

jQuery(function() {
    /** Intercept calls to tb_remove and tb_show for semaphore-like functionality */
    var w = window,
        tb_remove_orig = w.tb_remove,
        tb_show_orig = w.tb_show;
    w.tb_remove = function() {
        w.activePowerlayer = false;
        return tb_remove_orig.apply(null, arguments);
    }

    w.tb_show = function() {
      if (w.activePowerlayer) {
          return;
      }
      w.activePowerlayer = true;
      return tb_show_orig.apply(null, arguments);
    }
});

// find first preselected element in dropdown list, prepend it to all others in order to
// make it easier resetting long dropdonw lists
// leaves the original preselected value untouched
jQuery.fn.preselectedFirstInSelect = function() {
    var elements = $(this);

    elements.each(function() {
        var element = $(this);
        var selectedOption = element.find('option:selected');

        if (selectedOption.val() != '') {
            selectedOption.removeAttr('selected');
            selectedOption.clone().prependTo(element)/*.after('<option style="color:#666;" value="">(no selection)</option>')*/;

            // directly set as selected, in order to keep IE8 happy...
            element.find('option:first')[0].selected = 'selected';
        }
    });

    return elements;
}

