/**
 * Compact labels plugin
 */
(function($){$.fn.compactize=function(){return this.each(function(){var label=$(this),input=$('#'+label.attr('for'));input.focus(function(){label.hide();}).blur(function(){if(input.val()===''){label.show();}});window.setTimeout(function(){if(input.val()!==''){label.hide();}},50);});};})(jQuery);

/*
 * hrefID jQuery extention - returns a valid #hash string from link href attribute in Internet Explorer
 */
(function($){$.fn.extend({hrefId:function(){return $(this).attr('href').substr($(this).attr('href').indexOf('#'));}});})(jQuery);

function cumulativeOffset(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return{left:valueL,top:valueT};}
	
(function($){
	
		
	var cnSelect = function(el, options){
		
		var settings = {
			'controlClass' : 'select-a',
			'dropdownClass' : 'dropdown-a'
		};
		
		settings = $.extend(settings,options);
		
		var 
			$select = $(el).hide(),
			$options = $('<ul/>').addClass(settings.dropdownClass).hide(),
			$control = $('<div><a href="#"/></div>').addClass(settings.controlClass),
			lookupItems, documentClick,
			active = true;

		if ($select.hasClass('inactive')){
			$control.addClass(settings.controlClass+'-inactive');
			active = false;
		}		
				
		//activating and deactivating control
		$select.bind('cnSelect.deactivate',function(){
			active = false;
			$control.addClass(settings.controlClass+'-inactive');
		});
		
		$select.bind('cnSelect.activate',function(){
			active = true;
			$control.removeClass(settings.controlClass+'-inactive');
		});
						
		//click on the "select" control should open the dropdown and close on the next click
		$control.find('a').click(function(e){
			e.preventDefault();
			if (active === false) {
				return;
			}			
			
			if ($options.is(':visible')) {
				$(document).unbind('click',documentClick);			
			}
			else {
				$(document).bind('click',documentClick);			
			}
			$options.toggle();
			$options.find('a.current').trigger('focus');
		});

		lookupItems = $control.add($options).find('*');
		documentClick = function(e){
			if (lookupItems.index(e.target) === -1) {
				$(document).unbind('click',documentClick);
				$options.hide();
			}
		};

		//click on the dropdown item should close it and change value
		var optionClick = function(e){
			e.preventDefault();
			$options.hide();
			$(document).unbind('click',documentClick); //cleanup

			$control.find('a').text($(this).text());
			
			var prevValue = $select.val();			
			$select.val($(this).data('value'));
			if (prevValue !== $(this).data('value')) {
				$select.triggerHandler('change');
			}
		};

		var populateOptions = function(){
		    //populate data
		    $select.find('option').each(function(index, item){
			    var option = $('<a href="#">'+$(this).text()+'</a>');
						
			    option.data('value',$(this).attr('value'));		
			    option.click(optionClick);

			    var li = $('<li/>');
			
    			if (index === 0) {
	    			li.addClass('first');
		    	}
			
    			li.append(option);
	    		$options.append(li);
    		});
		    //activate first option
		    $options.find('a:first').triggerHandler('click');
        };

        //populate the options on page load
        populateOptions();

        //allow a caller to repopulate if the select options are changed
        $select.bind('cnSelect.repopulate',function(){
            $options.empty();
		    populateOptions();
        });

		//append controls to document
		$select.after($control);

		var pos = cumulativeOffset($control.get(0));
		
		$options.css({
			'top' : pos.top + $control.height() - 1,
			'left': pos.left
		});
		
		var w = $control.width()-27	;
		if (w >= 150) {
			$options.css({
				'width' : w
			});					
		}	
							
		$('body').append($options);
		
		if ($.browser.msie && $.browser.version == '6.0') {
			if ($options.height() > 150) {
				$options.css('height',150);
			}
		}							
	};
	
	//setup as a plugin
	$.fn.cnSelect = function(){
		var options = arguments[0] || {};
		return $(this).each(function(){
			return new cnSelect(this,options);
		});
	};
})(jQuery);

(function($){
	var cnTooltip = function(el, options){
		this.settings = {
			top : 0,
			left : 0, 
			align : 'left'
		};
		
		this.settings = $.extend(this.settings, options);
		
		this.$trigger = $(el);
		this.$target = $(this.$trigger.hrefId());
		this.isOpened = false;
		
		if (this.$target.length === 0) {
			return;
		}
				

		var position = cumulativeOffset(this.$trigger.get(0));		
		
		//fetch actual height of the target, then hide it (can't fetch height of a hidden elemenet)		
		var boxHeight = this.$target.height();
		var boxWidth = this.$target.width();
		this.$target.hide();
		
		this.settings.top = position.top - boxHeight + this.settings.top;
		this.settings.left = position.left + this.settings.left;
		
		if (this.settings.align === 'right'){
			this.settings.left = this.settings.left - boxWidth + this.$trigger.width();
		}
		
		var self = this;
		
		this.$trigger.click(function(e){
			e.preventDefault();
		}).mouseenter(function(e){
			self.open();
		}).mouseleave(function(e){
			self.close();
		});		
	};
	
	cnTooltip.prototype.open = function(){
		//do not run if there is an already opened tooltip
		if (this.isOpened) {
			return;
		}					
		this.isOpened = true;
		
		//reposition the tooltip box
		this.$target.css({
			'top': this.settings.top,
			'left': this.settings.left
		});
		
		if ($.browser.msie) {
			this.$target.show();
			return;
		}
		
		this.$target.fadeIn('fast');				
	};
	
	cnTooltip.prototype.close = function(){
		var self = this;
		
		if (this.isOpened === false) {
			return;
		}
		
		var onBoxHide = function(){
			self.isOpened = false;
			self.$target.css('top','-999em');						
		};
						
		if ($.browser.msie) {
			this.$target.hide();
			onBoxHide();
		}
		else {
			this.$target.fadeOut('fast',onBoxHide);
		}		
	};
	
	$.fn.cnTooltip = function(){
		var options = arguments[0] || {};

		return $(this).each(function(){
			return new cnTooltip(this, options);
		});
	};
})(jQuery);

/*
 * Scripts
 *
 */
jQuery(function($) {
 
	var Engine = {
		utils : {
			links : function(){
				$('a[rel*=external]').click(function(e){
					e.preventDefault();
					window.open($(this).attr('href'));						  
				});
			},
			mails : function(){
				$('a[href^=mailto:]').each(function(){
					var mail = $(this).attr('href').replace('mailto:','');
					var replaced = mail.replace('/at/','@');
					$(this).attr('href','mailto:'+replaced);
					if($(this).text() == mail) {
						$(this).text(replaced);
					}
				});
			}
		},
		enhancements : {
		    confirms : function(){
		        $('#delete_group').click(function(){
                    return confirm('Are you sure you want to delete this exchange? There is no undo.'); 
		        });
		        
		        $('#remove_participant').click(function(){
                    return confirm('Are you sure you want to remove this participant? There is no undo.'); 
		        });
		    },
		    actions : function(){
		        $('#show_detail_images').click(function(){
                    $('#detail_images').show()
		            return false;
		        }),

		        $('.hide_detail_images').click(function(){
                    $('#detail_images').hide()
		            return false;
		        }),
		        
		        $('#detail_images .next_arrow').click(function(){
		            var thisId = $(this).attr("href")
                    $('#detail_image_' + thisId).hide();
                    $('#detail_image_' + (parseInt(thisId) + 1)).show();
                    return false;
		        });

		        $('#detail_images .previous_arrow').click(function(){
		            var thisId = $(this).attr("href")
                    $('#detail_image_' + thisId).hide();
                    $('#detail_image_' + (parseInt(thisId) - 1)).show();
                    return false;
		        });

		        $('.option-a .button-b').click(function(){
		            $('.option-a .button-b').hide();
		            $('.edit-section-a').show();
		            $('#id_name').focus();
		            return false;
		        });
                
                $('.edit-section-a .button-cancel').click(function(){
                    $('.edit-section-a input').attr("value", "");
		            $('.option-a .button-b').show();
		            $('.edit-section-a').hide();                    
		            return false;
                });

                // Edit wishlist item
                $('#wishlist .button-edit').click(function(){
                    var parent = $(this).parents('.item')
                    var edit = parent.next('.edit-wishlist')
                    parent.hide()
                    edit.show()
                    return false; 
                });

                // Cancel editing wishlist item
                $('.edit-wishlist .button-cancel').click(function(){
                    var parent = $(this).parents('.edit-wishlist')
                    var display = parent.prev('.item')
                    parent.hide()
                    display.show()
                    return false; 
                });

                // Delete wishlist item
                $('.edit-wishlist .button-remove').click(function(){
                    var wishId = $(this).nextAll('input.hiddenId').val()
                    var edit = $(this).parents('.edit-wishlist')
                    var display = edit.prev('.item')
                    $.ajax({
                        type: "POST",
                        url: "/delete_wish/" + wishId + "/",
                        dataType: 'json',
                        success: function(data) {
                            errorCheck(data)
                            if (data.success) {
                                edit.remove()
                                display.remove()
                                updateCounters()
                            }
                        }
                    });
                    return false; 
                });

                // Save wishlist item
                $('.edit-wishlist .button-save').click(function(){
                    var wishId = $(this).nextAll('input.hiddenId').val()
                    var edit = $(this).parents('.edit-wishlist')
                    var display = edit.prev('.item')
                    var description = $("#description_" + wishId).val()
                    var url = $("#url_" + wishId).val()
                    dataString = "description=" + description + "&url=" + url
                    $.ajax({
                        type: "POST",
                        url: "/manage_wish/" + wishId + "/",
                        data: dataString,
                        dataType: 'json',
                        success: function(data) {
                            errorCheck(data)
                            if (data.success) {
                                $("#item_wrap_" + wishId + " span.description").html(description)
                                if (data.url_html) {
                                    // Insert the url paragraph
                                    $("#item_wrap_" + wishId + " h3").after(data.url_html)
                                }
                                $("#item_wrap_" + wishId + " p.url a").html(url)
                                display.show()
                                edit.hide()
                            }
                        }
                    });
                    
                    return false; 
                });

                // Reorder wishlist items
                $('#wishlist').sortable({ 
                    axis: 'y', 
                    items: 'div.item_wrap',
                    handle: '.counter', 
                    update: function(event, ui) { 
                        data = $('#wishlist').sortable('serialize')
                        $.ajax({
                            type: "POST",
                            url: "/update_wish_order/",
                            data: $('#wishlist').sortable('serialize'),
                            dataType: 'json',
                            success: function(data) {
                                errorCheck(data)
                                if (data.success) {
                                    updateCounters()
                                };
                            }
                        });
                    }
                });

                function updateCounters() {
                    $('.counter').each(function(i){
                        var count = i + 1;
                        $(this).html(count);
                    });
                };

                function updateYears() {
                    $('.year').each(function(i){
                       $(this).html((new Date).getFullYear() - i - 1)
                    });                    
                };
                updateYears();

                function errorCheck(data) {
                    if (data.error) {
                        alert(data.error)
                    }
                }

                // Reorder history
                $('#history').sortable({
                    axis: 'y',
                    handle: '.handle',
                    update: function(event, ui) {
                        $.ajax({
                            type: "POST",
                            url: "/update_history/",
                            data: $('#history').sortable('serialize'),
                            dataType: 'json',
                            success: function(data) {
                                errorCheck(data)
                                if (data.success) {
                                    updateYears()
                                };
                            }
                        });
                    }
                });
                
                // Add history
                $('#add_history .button-d-add').click(function(){
                    var id = $('#add_history select').val()
                    $.ajax({
                        type: "POST",
                        url: $('#add_history').attr("action") + id + '/',
                        data: "",
                        dataType: 'json',
                        success: function(data) {
                            if (data.html) {
                                $('#history').prepend(data.html)
                                updateYears()
                                // TODO: We need to initialize the X (delete) link that was just added
                            }
                        }
                    });
                    return false;
                });
                
                // Add restriction
                $('#add_restriction .button-d-add').click(function(){
                    var id = $('#add_restriction select').val()
                    $.ajax({
                        type: "POST",
                        url: $('#add_restriction').attr("action") + id + '/',
                        data: "",
                        dataType: 'json',
                        success: function(data) {
                            if (data.html) {
                                $('#restrictions').prepend(data.html)
                                // TODO: We need to initialize the X (delete) link that was just added
                            }
                        }
                    });
                    return false;
                });

                // Delete history
                $('#history .button-d-remove').click(function(){
                    $.ajax({
                        type: "POST",
                        url: $(this).attr("href"),
                        data: "",
                        dataType: 'json',
                        success: function(data) {
                            if (data.success) {
                                $('#history_' + data.historyId).remove()
                            }
                        }
                    });
                    return false;                    
                });
                
                // Delete restriction
                $('#restrictions .button-d-remove').click(function(){
                    $.ajax({
                        type: "POST",
                        url: $(this).attr("href"),
                        data: "",
                        dataType: 'json',
                        success: function(data) {
                            if (data.success) {
                                $('#restriction_' + data.restrictionId).remove()
                            }
                        }
                    });
                    return false;
                });

                // Retrieve password
                $('.forgot-password-a button').click(function(){
                    // Validate 
                    var email = $("input#f-remind").val();
                    if (email == "") {
                        alert('Please enter an email.')
                        return false;
                    }
                    
                    var dataString = "email=" + email

                    $.ajax({
                        type: "POST",
                        url: "/forgot_password/",
                        data: dataString,
                        dataType: 'json',
                        success: function(data) {
                            errorCheck(data)
                            if (data.success) {
                                alert('We just sent you a new password.')
                                $("input#f-remind").attr("value", "")
                                $("#id_username").focus()
                            };
                            }
                    });
                    return false;
                })

                // Add user to group
                $('.edit-section-a .button-save').click(function(){
                    // Validate the form.
                    var name = $("input#id_name").val();
                    if (name == "") {
                        alert('Please enter a name.')
                    } else {
                        var email = $("input#id_email").val();
                        if (email == "") {
                            alert('Please enter an email.')
                            return false;
                        }
                    }

                    // Send data to server
		            var dataString = 'name='+ name + '&email=' + email
		            //alert (dataString); return false;

                    $.ajax({
                        type: "POST",
                        url: $('.edit-section-a form').attr("action"),
                        data: dataString,
                        dataType: 'json',
                        success: function(data) {
                            errorCheck(data)
                            if (data.html) {
                                $('.listing-a').prepend(data.html)
                                // Add html back to this page.
                    
                                // Return to non-edit state.
                                $('.edit-section-a input').attr("value", "");
                                $('.option-a .button-b').show();
                                $('.edit-section-a').hide();
                            };
                            }
                    });
                    
                    return false;
                });

		    }
		}
	};

	Engine.utils.links();
	Engine.utils.mails();
	
	Engine.enhancements.actions();
	Engine.enhancements.confirms();
});
