function getCookie(name) {
    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;
}

function show_overlay() {
	hide_overlay();
	$('body').prepend('<div id="overlay">&nbsp;</div>');
	setup_overlay_height();
	$('#overlay').fadeIn('fast');
}
function hide_overlay() {
	$('#overlay').remove();
}
function setup_overlay_height() {
	body_height = $(document).height();
	$('#overlay').css('height', body_height);
}
function hide_popups() {
	if ($('.popup').length) { $('.popup').fadeOut('fast') };
	$('#ajax-holder').remove();
	hide_overlay();
}

/* Favorites actions */
function addClickHandlers() {
	$("a.favicon, a.fav, a.faved").live('click', function() {
		if ($(this).attr('rel').length > 0) {
			var id = $(this).attr('rel');
			var action = ($(this).hasClass('faved')) ? "remove" : "add";
			var fav = $(this);
			$.getJSON("/faves/action/"+id+"/"+action+"/", function(json){
				if (json['success']) {
					if (action == 'add') {
						$(fav).addClass('faved').removeClass('fav');
						if ($(fav).hasClass('tooltip-favorite')) $(fav).text('Unfavorite');
					} else if(action == 'remove') {
						$(fav).addClass('fav').removeClass('faved');
						if ($(fav).hasClass('tooltip-favorite')) $(fav).text('Favorite');
					}
				}
			});
		} else {
			// TODO: do login
		}
		return false;
	});

	// add rollover effect to BSA ads
	$('.ad-bottom .bsap').hover(function(){
		$(this).addClass('ads-border-js');
	}, function(){
		$(this).removeClass('ads-border-js');
	});
}
$(document).ready(addClickHandlers);

$(function(){

	$('.popup').center();

	$('form:not(.jqnone,.jqplain)').jqTransform();
	$('form.jqnone select').combobox({
		comboboxContainerClass: "select-container",
		comboboxValueContainerClass: "select-value-container",
		comboboxValueContentClass: "select-value-content",
		comboboxDropDownClass: "select-dropdown-container",
		comboboxDropDownButtonClass: "select-dropdown-button",
		comboboxDropDownItemClass: "select-dropdown-item",
		comboboxDropDownItemHoverClass: "select-dropdown-item-hover",
		comboboxDropDownGroupItemHeaderClass: "select-dropdown-item-header",
		comboboxDropDownGroupItemContainerClass: "select-dropdown-item-container"
	},{
		width: 308,
		animationSpeed: 'fast',
		height: '200px'
	});

	$('.popup .close').live('click', function() {
		hide_popups();
		return false;
	});

	$('#upload-profile-pic').live('submit', function() {
		$('#upload-profile-pic input.submit').attr('disabled', 'disabled');
		return false;

	});

	$('#overlay').live('click', function() {
		hide_popups();
	});

	$('a[rel=popup]').live('click', function() {
		$('#ajax-holder').remove();
		var href = $(this).attr('href');
		var login = false;
		var feedback = false

		if ($(this).hasClass('login-link')) login = true;
		if ($(this).hasClass('popup-feedback')) feedback = true;
		$('body').append('<div id="ajax-holder">&nbsp;</div>');
		var $this = $(this);
		$('#ajax-holder').load(href, function() {
			if (login) {
				$('#login-form').attr('action', $('#login-form').attr('action') + '?next=/prints/');
			}
			if (feedback) {
				$('#feedback-form').jqTransform();
				$('#feedback-form').submit(function(){
					var form_data = $(this).serialize();
					var form = $(this);
					$('.error', form).hide();
					$.ajax({
						type: 'POST',
						url: '/contact/feedback/',
						data: form_data,
						success: function(data) {
							if (data == 'OK') {
								$('.error', form).hide();
								$('.column-left', form).html('<h3>Thank you!</h3><br />Your inquiry has been submitted to the PrintedPiece bug tracker.<br />We will tackle this issue as soon as possible!.');
								window.setTimeout(function() {
									hide_popups();
								}, 5000);
							} else {
								$('.error', form).show();
							}
						}
					});
					return false;
				});
			}
			$('.popup').center();
		});
		return false;
	});

	$('.out .reset').live('click', function() { hide_popups(); });

	$('a[rel=popupupload]').live('click', function() {
		$('#ajax-holder').remove();
		var href = $(this).attr('href');
		$('body').append('<div id="ajax-holder">&nbsp;</div>');
		var $this = $(this);
		$('#ajax-holder').load(href, function() {
			$('.popup').center();
			$('.reset', this).click(function() { hide_popups(); });
			$('.submit', this).click(function() {
				if (!$('#accept-agreement').is(':checked')) {
					$('#loader-message > span').text('You need to agree with the Terms and Conditions');
				} else {
					uploader.submit();
				}
				return false;
			});
			var uploader = new AjaxUpload('uploader', {
				'action'       : '/profile/upload/profile-image/',
				'name'         : 'profile_img',
				'autoSubmit'   : false,
				'hoverClass'   : 'uploader-hover',
				'onComplete' : function(file, response) {
					if (response != 'OK') {
						$('#loader-message > span').text(response + '<br />Please try again.');
						$('#loader-message > img').hide();
					} else {
						$('#loader-message > span').text('File uploaded successfully!');
						$('#loader-message > img').hide();
						$('#user-profile-pic').attr('src', $('#user-profile-pic').attr('src') + '?123');
						hide_popups();
					}
				},
                                'data': {
                                        'csrfmiddlewaretoken': getCookie('csrftoken')
                                },
				'onChange'   : function(file, extension) {
					$('#uploader-path').val(file);
				},
				'onSubmit'   : function(file, extension) {
					$('#loader-message > img').show();
					$('#loader-message > span').text('Uploading...');
				}
			});

		});
		return false;
	});

	$('.user-sidebar ul a').click(function(){
		$('.user-sidebar ul a').removeClass('active');
		$(this).addClass('active');
		var href = $(this).attr('href');
		$('.section').hide();
		if (href == '#cancel-account') $('.form-buttons').hide();
		else $('.form-buttons').show();
		$(href).fadeIn('fast');
		return false;
	});

	$('a[rel=popupremove]').live('click', function() {
		$('#ajax-holder').remove();
		var href = $(this).attr('href');
		$('body').append('<div id="ajax-holder">&nbsp;</div>');
		var $this = $(this);
		$('#ajax-holder').load(href, function() {
			$('.popup').center();
			$('.reset', this).click(function() { hide_popups(); });
			$('.submit', this).click(function() {
				$.post('/profile/remove/profile-image/', function(data) {
					if (data == 'OK') {
						$('#user-profile-pic').attr('src', '/static/css/images/profile-img1.jpg');
						hide_popups();
					}
				});
				return false;
			});
		});
		return false;
	});

	$('.close-btn a').live('click', function() {
		var anon = (($(this).attr('rel') == 0)?true:false);
		if ($(this).attr('href') == '#close') {
			$('.close-btn a').attr('href', '#open');
			$('.text-btn').text('Show Banner');
			$('.img-btn > img').attr('src', '/static/css/images/home-banner-btn-open.png');
			$('#home-banner').slideUp('normal', function() {
				if (!anon) {
					$.post('/profile/banner-off/', {action: 'close'});
				}
				$.cookie('banner-off', '1', {'expires': 150});
			});
			$('.home-boxes .row-2, .home-boxes .row-4').fadeIn();
		} else {
			$('.close-btn a').attr('href', '#close');
			$('.text-btn').text('Hide Banner');
			$('.img-btn > img').attr('src', '/static/css/images/home-banner-btn-close.png');
			$('#home-banner').slideDown('normal', function() {
				if (!anon) {
					$.post('/profile/banner-off/', {action: 'open'});
				}
				$.cookie('banner-off', null);
			});
			$('.home-boxes .row-2, .home-boxes .row-4').fadeOut();
		}
		return false;
	});

	$(document).keypress(function(e){
		if(e.keyCode==27){
			hide_popups();
		}
	});

    $('.blink').focus(function() {
        if(this.title==this.value) {
			$(this).removeClass('not-modified');
            this.value = '';
        }
    }).blur(function(){
        if(this.value=='') {
			$(this).addClass('not-modified');
            this.value = this.title;
        }
    });

    $('.category-select').click(function(){
    	$(this).find('.drop-down').toggle();
    })

	$('.membership-form').submit(function(){
		var val = $('input[name=membership]:checked', this).val();
		if (val == 'Free') {
			window.location = '/welcome/';
		} else {
			window.location = '/upgrade/payment/';
		}
		return false;
	});
    /*
    $('.admin-nav a').click(function(){
    	$('form').jqTransform();
    	var index = $(this).parent().parent().find('a').index(this);
    	$('#tabbed-content .tab').hide();
    	$('#tabbed-content .tab').eq(index).show();

    	$(this).parent().parent().find('a').removeClass('active');
    	$(this).addClass('active');
    });
    */

    $('#tabbed-content .profile .social-links .holder').hover(function() {
    	$(this).find('.tooltip').show();
    }, function() {
    	$(this).find('.tooltip').hide();
    });

	$('a.follow').click(function() {
		var icon = $(this).hasClass('icon');
		var obj = $(this);
		var url;
		usr = $(this).attr('rel');
		if ($(this).attr('href') == '#follow') {
			url = '/user/follow/' + usr + '/';
			$.post(url, {}, function(data) {
				if (data.success) {
					if (icon) {
						$('img', obj).attr('src', '/static/css/images/icon-check-green.gif')
					} else {
						$('.follow').addClass('followblue').text('Following').attr('href', '#unfollow');
						$('#following-'+usr).text('unfollow')
					}
					$('#following-'+usr).attr('href', '#unfollow');
				}
			}, 'json');
		} else if ($(this).attr('href') == '#unfollow') {
			url = '/user/unfollow/' + usr + '/';
			$.post(url, {}, function(data) {
				if (data.success) {
					if (icon) {
						$('img', obj).attr('src', '/static/css/images/icon-cross-red.gif')
					} else {
						$('.follow').removeClass('followblue').text('Follow User').attr('href', '#follow');
						$('#following-'+usr).text('follow');
					}
					$('#following-'+usr).attr('href', '#follow');
				}
			}, 'json');
		}
		return false;
	});

  	// Navigation  Drop Down
  	$('#navbar ul li').hover(
  		function(){
  			if ( $(this).find('ul:eq(0)').length ) {
  				$(this).find('a:eq(0)').addClass('hover');
  			};

  			$(this).find('ul:eq(0)').show();
  		},
  		function(){
			$(this).find('ul:eq(0)').hide();
			$(this).find('a:eq(0)').removeClass('hover');
  		}
  	);

	$('#nav-6').click(function(){
		$('#navbar ul li a').removeClass('active');
		if ($('.subnav-cats').is(':visible')) {
			$('.subnav-cats').slideUp();
			$(this).removeClass('active');
		} else {
			$('.subnav-cats').slideDown();
			$(this).addClass('active');
		}
		return false;
	});

	$('.main-columns > li').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover')});

  	// Search Module
	$('#search .nav a').click(function(){
		var attr = $(this).attr('href');
		if (attr == '#green') {
			$('#search').removeClass('search-yellow-tab').addClass('search-green-tab');
			$('#yellow-tab-content').hide();
			$('#green-tab-content').show();
		} else {
			$('#search').removeClass('search-green-tab').addClass('search-yellow-tab');
			$('#green-tab-content').hide();
			$('#yellow-tab-content').show();
		}
		return false;
	});

	$('#search-form').submit(function() {
		if ($('input.field', this).hasClass('not-modified')) $('input.field', this).val('');
	});
	$('#business-search-form').submit(function() {
		if ($('input.field1', this).hasClass('not-modified')) $('input.field1', this).val('');
		if ($('input.field2', this).hasClass('not-modified')) $('input.field2', this).val('');
	});

  	$('.advertisement .close').click(function() {
  		return false;
	});

	// Toggle Map

	$('.map-toggle').click(function(){
		$(this).toggleClass('map-show');
		if ( $(this).hasClass('map-show') ) {
			$(this).html('Show Map');
		}
		else { $(this).html('Hide Map'); }

		$(this).parents('#widebox').find('.map').toggle();

		return false;
	});

	// Quick Search
	$('.quick-search .trigger').click(function(){
		$(this).toggleClass('trigger-active');
		$(this).parent().find('ul').slideToggle();
		return false;
	});

	// $('.show-map').click(function(){ displayMap($(this).attr('rel')); return false; })

	// Delete Updates
	$('.updates .update-remove').click(function() {
		var upd_id = $(this).attr('rel');
		var el = $(this).parents('.update');
		$.ajax({
			type: 'get',
			url:  '/update/remove/'+upd_id,
			success: function(data) {
				if (data == 'OK') {
					el.fadeOut('fast');
				}
			}
		});
		return false;
	})


	// Payment Methods
	$('.payment-method .nav a').click(function() {
		return false;
	});

	$('input[name=membership-preference]').click(function(){
		var val = $(this).val();
		$('#paypal-buttons div').hide();
		$('#paypal'+val).show();
		$('#subscription_type').val(val);
	});
});

jQuery.fn.center = function(loaded) {
    var obj = this;
    body_width = parseInt($(window).width());
	body_height = parseInt($(window).height());
	block_width = parseInt(obj.width());
	block_height = parseInt(obj.height());

	left_position = parseInt((body_width/2) - (block_width/2)  + $(window).scrollLeft());
	if (body_width<block_width) { left_position = 0 + $(window).scrollLeft(); };
	top_position = parseInt((body_height/2) - (block_height/2) + $(window).scrollTop());
	if (body_height<block_height) { top_position = 0 + $(window).scrollTop(); };


    if(!loaded) {

    	obj.css({'position': 'absolute'});
		obj.css({'left': left_position, 'top': top_position});
        $(window).bind('resize', function() {
        	obj.center(!loaded);
    	});
		$(window).bind('scroll', function() {
        	obj.center(!loaded);
    	});

    } else {
        obj.stop();
        obj.css({'position': 'absolute'});
        obj.animate({'left': left_position, 'top': top_position}, 200, 'linear');
    }
}

// csrf protection
$(document).ajaxSend(function(event, xhr, settings) {
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

