function openWindow(url, name, w, h, args) {
	if(!args)
		args = "";

	var left = (screen.width  / 2) - (w  / 2);
	var top  = (screen.height / 2) - (h  / 2);
	return window.open(url, name, 'width='+w+',height='+h+',scrollbars=yes,left='+left+',top='+top+","+args);
}

function openMagazine(shortcode) {
	var w = parseInt(screen.width / 1.5);
	var h = parseInt(screen.height / 1.5);
	var l = parseInt((screen.width  / 2) - (w  / 2));
	var t  = parseInt((screen.height / 2) - (h  / 2));
	var win = null;

	if(shortcode) {
		win = open(BASE_URL.replace(/\/$/, '') + "/p/" + shortcode, 'magazine_view', 'width='+w+', height='+h+', left='+l+', top='+t+', scrollbars=no, resizable=yes');
		win.focus();
	} else {
		alert("Please provide a correct shortcode in the script.");
	}
	return false;
}

function previewPublication(shortcode, page_num) {
    var w = parseInt(screen.width / 1.5);
    var h = parseInt(screen.height / 1.5);
    var l = parseInt((screen.width  / 2) - (w  / 2));
    var t  = parseInt((screen.height / 2) - (h  / 2));
    var win = null;
    var path = null;

    if (shortcode) {
		path = BASE_URL.replace(/\/$/, '') + "/p/" + shortcode + "/" + page_num + "?media_preview=True";
		win = open(path, 'magazine_preview', 'width=' + w + ', height=' + h + ', left=' + l + ', top=' + t + ', scrollbars=no, resizable=yes');
        if (win) {
            win.focus();
        } else {
            alert("Turn off your popup blocker to preview the changes.");
        }

	} else {
        alert("Unable to make the preview.");
	}
	return false;
}

function previewSkin(path) {
    var w = parseInt(screen.width / 1.5);
    var h = parseInt(screen.height / 1.5);
    var l = parseInt((screen.width  / 2) - (w  / 2));
    var t  = parseInt((screen.height / 2) - (h  / 2));
    var win = null;

    if (path) {
		win = open(path, 'skin_preview', 'width=' + w + ', height=' + h + ', left=' + l + ', top=' + t + ', scrollbars=no, resizable=yes');
        if (win) {
            win.focus();
        } else {
            alert("Turn off your popup blocker to preview the skin.");
        }

	} else {
        alert("Unable to show the skin preview.");
	}
	return false;
}

function showEmbed(id) {
	if(window.ENABLE_EFFECTS) {
		var fadeEmbedIn = function() {
			$(this)
				.show()
				.animate({ 'opacity': 1 }, 300, 'swing');

			$("#embed_code_background_"+id)
				.show()
				.animate({ 'opacity': 0.85 }, 300, 'swing');

			$("#embed_code_content_"+id)
				.css("padding-left", "20px")
				.show()
				.animate({ 'paddingLeft': "10px"}, { queue: false, duration: 300, easing: 'swing'  })
				.animate({ 'opacity': 1 }, 300, 'swing');
		};
		$("#embed_code_background_" + id).fadeTo(1, 0);
		$("#embed_code_" + id).fadeTo(1, 0, fadeEmbedIn);
	} else {
		$('#embed_code_' + id).show();
		$('#embed_code_background_' + id).css("height", "500px").css("width", "500px").show();
		$('#embed_code_content_' + id).css("padding-left", "10px").show();
	}
	return false;
}

function hideEmbed(id) {
	if(window.ENABLE_EFFECTS) {
		$('#embed_code_content_' + id)
			.animate({ 'paddingLeft': "0px"}, { queue: false, duration: 300 })
			.animate({ 'opacity': 0 }, 300, 'swing', function() { $(this).hide() });

		$('#embed_code_' + id).animate({ 'opacity': 0 }, function() { $(this).hide() });
	} else {
		$('#embed_code_background_' + id).hide();
		$('#embed_code_content_' + id).hide();
		$('#embed_code_' + id).hide();
	}
	return false;
}

document.viewport = {
  getDimensions: function() {
	var dimensions = { };

	var wd = function(d) {
		var D = d;
		var d = d.toLowerCase();
		dimensions[d] = ($.browser.safari && !document.evaluate) ? self['inner' + D] :
		($.browser.opera) ? document.body['client' + D] : document.documentElement['client' + D];
	};
	wd("Width");
	wd("Height");

	return dimensions;
  },

  getWidth: function() {
	return this.getDimensions().width;
  },

  getHeight: function() {
	return this.getDimensions().height;
  },

  getScrollOffsets: function() {
	return [
	  window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
	  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop];
  }
};

function getPageSize() {
	 var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

var modalOverlay = null;
var modalContent = null;
var modalCallback = null;
var modalHideObjects = null;
function modalConfirm(dialogContentId, callback) {
	var d = $("#modalDialog");
	var size = getPageSize();

	if($.browser.msie) {
		d[0].style.width = size[0] + "px";
		d[0].style.height = size[1] + "px";
	}

	var dialog = $("#"+dialogContentId);

	var arrayPageScroll = document.viewport.getScrollOffsets();
	var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 2) - (dialog.height()/2);
	var lightboxLeft = arrayPageScroll[0] + (document.viewport.getWidth() / 2) - (dialog.width()/2);
	dialog.css("top", lightboxTop + 'px').css("left", lightboxLeft + 'px');

	modalHideObjects = $("select, applet, object").css("visibility", "hidden");
	d.fadeTo(1, 0.0, function() { $(this).show().fadeTo(250, 0.5); });
	dialog.fadeTo(1, 0.0, function() { $(this).show().fadeTo(250, 1); });
	modalOverlay = d;
	modalContent = dialog;
	modalCallback = callback;

	return false;
}

function returnModalConfirm(returnVal) {
	var c = modalCallback;
	modalOverlay.fadeOut(100);
	modalContent.fadeOut(100);
	modalHideObjects.css("visibility", "visible");
	modalOverlay = null;
	modalContent = null;
	modalCallback = null;
	c(returnVal);
	return false;
}

jQuery.fn.shake = function(){
	var shakeSpeed = 50;
	var moveBy = 10;
     this.each(function(init){
          var jqNode = $(this);
          jqNode.animate({ left: "-=" + moveBy},shakeSpeed / 2);
          for (var x = 1; x <= 2; x++){
               jqNode.animate({ left: "+=" + moveBy },shakeSpeed)
               .animate({ left: "-=" + moveBy },shakeSpeed)
          }
          jqNode.animate({ left: "+=" + moveBy },shakeSpeed / 2);
     });
	 return this;
}


jQuery.fn.pulsateOpacity = function(callback) {
	return this.each(function() {
		var mm = $(this);
		mm.fadeTo(100, 0.2, function() {
			mm.fadeTo(600, 1, function() {
				if(callback != undefined)
					callback();
			});
		});
	});
}

jQuery.fn.pulsate = function(callback, color) {
	return this.each(function() {
		if(color == undefined)
			color = "#ffffff";
		var mm = $(this);

		var clone = mm.clone();
		clone.click(function() { return false }); // * make it doesn't do anything while animating
		clone.css("background", color).css("position", "absolute").css("z-index", "999").fadeTo(1, 0, function() {
			mm.before(clone);
			clone.fadeTo(150, 0.5, function() {
				clone.fadeTo(600, 0, function() {
					clone.remove();
					if(callback != undefined)
						callback();
				});
			});
		});
	});
}

// * bubble stuff {{{
function showBubble(bubbleContentId, atElement) {
	// * helper for focusing username field after animation
	var focusInput = function() {
		$("#login_bubble_container .bubbleContent:visible :input:first").focus();
	}

	if(bubbleContentId != undefined)
		$("#login_bubble_container #"+bubbleContentId).show();

	if(atElement == undefined)
		atElement = $("#loginMenuLink")

	var bubbleWidth = $("#login_bubble_container").width();
	var bubbleLeft  = atElement.offset().left + (atElement.width() / 2) + 22; // * 22 is the width of the rightmost column in the bubble
	var bubbleTop   = atElement.offset().top + atElement.height() + 10;
	$("#login_bubble_container").css( { left: (bubbleLeft - bubbleWidth) + "px", top: bubbleTop + "px" });

	// * animate puff-in if *un-visible*!
	if(!$("#login_bubble_container").is(":visible")) {
		var fadeBubbleIn = function() {
			$("#login_bubble_container")
				.css("margin-top", "-10px")
				.show()
				.animate({ 'marginTop': '0px'}, { queue: false, duration: 200, easing: 'swing'  })
				.animate({ 'opacity': 1 }, { queue: false, duration: 200, easing: 'swing', complete: focusInput })
			;
		};

		// * ie6+7 has problems with 24bits alpha and (opacity) filters. workaround: drop the fade-in
		if(!$.browser.msie) {
			// * initially hide the puffup
			$("#login_bubble_container").fadeTo(1, 0, fadeBubbleIn);
		} else {
			$("#login_bubble_container").show();
		}
	}
	return false;
}

function hideBubble() {
	var hideContentFunc = function() {
		$("#login_bubble_container .bubbleContent").hide();
	};

	// * ie6+7 has problems with 24bits alpha and (opacity) filters. workaround: drop the fade-in
	if(!$.browser.msie) {
		$("#login_bubble_container").fadeOut(150, hideContentFunc);
	} else {
		$("#login_bubble_container").hide();
		hideContentFunc();
	}
}

function showBubbleContent(contentId) {
	$("#login_bubble_container .bubbleContent").hide();
	$("#login_bubble_container #"+contentId+".bubbleContent").show();
}

var lastKeyCode = -1;
$(document).keydown(function(e) {
	if(e.keyCode == 27) {
		hideBubble();
		e.stopPropagation();
		//e.cancelDefault();
		return false;
	}
	/*
	// * escape closes the puff-up if pressed twice
	if(e.keyCode == 27 && lastKeyCode == 27) {
		hideBubble();
		e.stopPropagation();
		e.cancelDefault();
		return false;
	}*/
	lastKeyCode = e.keyCode;
});
// * }}} bubble stuff

function openShopUploadModule(shopId) {
	var w = 728;
	var h = 342;
	var l = (screen.width  / 2) - (w  / 2);
	var t  = (screen.height / 2) - (h  / 2);

	var win = window.open('javascript: void(0);', 'upload_quick', 'width='+w+',height='+h+',left='+l+',top='+t);
	if(win.activateWindow) {
		win.activateWindow();
	} else {
		win.focus();
		win = window.open('/shop/'+shopId+'/upload/quick/', 'upload_quick', 'width='+w+',height='+h+',left='+l+',top='+t);
	}
}

function openAccountUploadModule() {
	var w = 728;
	var h = 342;
	var l = (screen.width  / 2) - (w  / 2);
	var t  = (screen.height / 2) - (h  / 2);

	var win = window.open('javascript: void(0);', 'upload_quick', 'width='+w+',height='+h+',left='+l+',top='+t);
	if(win.activateWindow) {
		win.activateWindow();
	} else {
		win.focus();
		win = window.open('/account/upload/quick/', 'upload_quick', 'width='+w+',height='+h+',left='+l+',top='+t);
	}
}

/* ------------------------ */
function ref(number) {
	if(number == 2) {
		jQuery("#slide-one").fadeOut(150);
		jQuery(".page-selector a").removeClass("active-btn");
		jQuery("#slide-two").delay(200).fadeIn(300);
		jQuery("a.ref-sel-2").addClass("active-btn");
	} else {
		jQuery("#slide-two").fadeOut(150);
		jQuery(".page-selector a").removeClass("active-btn");
		jQuery("#slide-one").delay(200).fadeIn(300);
		jQuery("a.ref-sel-1").addClass("active-btn");
	}
}

function share(place) {
		var url = encodeURIComponent(location.href.toString());
		var title = encodeURIComponent(document.title);

		switch(place) {
		case 'facebook':
				window.open('http://www.facebook.com/sharer.php?u='+url+'&t='+title, 'facebook',
                    'toolbar=no,width=700,height=400');
				break;
		case 'delicious':
				window.open('http://del.icio.us/post?url='+url+'&title='+title);
				break;
		case 'twitter':
				window.open('http://twitter.com/home?status='+url);
				break;
		case 'digg':
				window.open('http://digg.com/submit?phase=2&url=' + url + '&title=' + title);
				break;
		case 'su':
				window.open('http://www.stumbleupon.com/submit?url='+url);
				break;
		}
}

$(function() {
	    update_status();

	    // make pricing tables and others available for styling
	    $('table').each(
          function() {
		          $('tr', this).each(
                  function(i) {
			                $(this).addClass('row-'+(i+1));
			                $('td', this).each(function(j) {
				                                     $(this).addClass('col-'+(j+1));
			                                   });
		              });
	        });

	    // backwards compability
	    $('code[lang]').each(function() { var html = $(this).html(); $(this).wrap('<code language="'+$(this).attr('lang')+'">').parent().html(html); });

	    // for comparison chart
	    $('.comparison-chart tr:odd').addClass('odd');
	    $('.comparison-chart td').each(
          function() {
		          if($(this).text().substr(0,1).toLowerCase() == 'x') {
			            $(this).addClass('checkoff');
			            $(this).text('√' + $(this).text().substr(1));
		          }
	        });
	    $('.comparison-chart .help').hide().each(
          function() {
		          var dupe = $(this).parent().clone(false);
		          dupe.find("*").remove(); // remove all children (should only be help text)
		          $(this).prepend('<h3>'+dupe.text()+'</h3>');
		          $(this).parent().prepend('<div class="help-over"></div>');
	        });
	    $('.comparison-chart .help-over').hover(
		      function() { $(this).parent().find('.help').fadeIn('fast'); },
		      function() { $('.help').fadeOut('fast'); }
	    );
	    $('.sidebar .widget h2').append(
          '<img class="horns" src="/wp-content/themes/pagegangster-website/images/horns.png" />');

      // Horrible old dialogs. When time and will: make it sane.
			$("body").append(
'       <div id="login_bubble_container" class="bubbleContainer" style="display:none">' +
'			  <div class="closeButton pngfix" onclick="hideBubble()"></div>' +
'			  <table>' +
'				  <tr>' +
'					  <td class="btl"></td>' +
'					<td class="bt"></td>' +
'					<td class="btr"></td>' +
'				</tr>' +
'				<tr>' +
'					<td class="bml"></td>' +
'					<td class="bcontent">' +
'						<div id="shopSelector" class="bubbleContent">' +
'							<h2><span>Choose shop</span></h2>' +
'' +
'							<p></p>' +
'							<div style="text-align: right;">' +
'								<form action="." method="post" id="shopSelectForm">' +
'									<select id="shopSelectorDropdown" style="margin-top: 15px; margin-bottom: 15px; padding: 3px; width: 180px;"></select>' +
'									<input type="submit" value="Continue" id="shopSelectorButton" />' +
'								</form>' +
'							</div>' +
'							<p style="margin-top: 20px;">Not in the mood for reseller business? You could <a href="/account/logout/" id="shopLogout">logout</a> and come back later.</p>' +
'						</div>' +
'' +
'						<div id="accountSignupBox" class="bubbleContent">' +
'							<h2><span>Signup</span></h2>' +
'' +
'							<form id="signupForm" class="labelLayout" action="." method="post" onsubmit="return beginSignup()">' +
'								<p>Please fill in the form below and start with your brand new pagegangster account. </p>' +
'' +
'								<div class="bubbleFormErrorMessage"></div>' +
'' +
'								<p>' +
'									<label for="id_signup_email">Email:</label>' +
'									<input type="text" id="id_signup_email" name="email" /><br/>' +
'								</p>' +
'								<p>' +
'									<label for="id_signup_password">Password:</label>' +
'									<input type="password" id="id_signup_password" name="password" /><br/>' +
'								</p>' +
'								<p>' +
'									<label for="id_signup_repeat_password">Repeat:</label>' +
'									<input type="password" id="id_signup_repeat_password" name="repeat_password" /><br/>' +
'								</p>' +
'								<p>' +
'									<input type="checkbox" id="id_signup_newsletter" name="newsletter" />' +
'									<label class="checkboxLabel" for="id_signup_newsletter">Receive newsletter</label>' +
'								</p>' +
'								<p>' +
'									<input type="checkbox" id="id_signup_terms" name="terms" />' +
'									<label class="checkboxLabel" for="id_signup_terms">I ACCEPT THE <a href="/eng/page/terms_of_use/" target="_blank">terms of use</a></label>' +
'								</p>' +
'' +
'								<div class="buttonContainer">' +
'									<div class="buttonRightContainer">' +
'										<input type="submit" id="signup_box_submit" value="Signup"/>' +
'									</div>' +
'								</div>' +
'							</form>' +
'						</div>' +
'						<div id="accountSignupReponseBox" class="bubbleContent">' +
'							<h2><span>Congratulations!</span></h2>' +
'' +
'							<p>You have created a new account. You will receive an e-mail within a few minutes with a link to activate your new account.</p>' +
'							<p>Please check your inbox.</p>' +
'							<p>' +
'								Best regards,<br/>' +
'								The Pagegangster Crew' +
'							</p>' +
'							<p>' +
'								<input type="button" value="Close" onclick="hideBubble()" />' +
'							</p>' +
'						</div>' +
'' +
'						<div id="accountLoginBox" class="bubbleContent">' +
'							<h2><span>Login</span></h2>' +
'' +
'							<form id="loginForm" class="labelLayout" action="." method="post" onsubmit="return beginLogin()" >' +
'								<p>Enter login credentials to access your account.</p>' +
'' +
'								<div class="bubbleFormErrorMessage"></div>' +
'' +
'								<p>' +
'									<label for="id_email">Email:</label>' +
'									<input type="text" id="id_email" name="email" /><br/>' +
'								</p>' +
'' +
'								<p>' +
'									<label for="id_password">Password:</label>' +
'									<input type="password" id="id_password" name="password" />' +
'								</p>' +
'' +
'								<div class="buttonContainer">' +
'									<div class="buttonRightContainer">' +
'										<input type="submit" id="login_box_submit" value="Login"/>' +
'									</div>' +
'								</div>' +
'' +
'								<p class="forgotPasswordP">' +
'									<a id="accountForgotPasswordLink" href="#">Forgot your password?</a>' +
'								</p>' +
'							</form>' +
'						</div>' +
'' +
'						<div id="accountForgotPassword" class="bubbleContent">' +
'							<h2><span>Forgot password</span></h2>' +
'' +
'							<form id="forgotPasswordForm" class="labelLayout" action="." method="post">' +
'								<p>' +
'									Enter your e-mail address and an e-email will be sent to you that allows you to change the password of your account.' +
'								</p>' +
'' +
'								<div class="bubbleFormErrorMessage"></div>' +
'' +
'								<p>' +
'									<label for="id_forgot_password_email">E-mail:</label>' +
'									<input type="text" id="id_forgot_password_email" name="email" /><br>' +
'								</p>' +
'' +
'								<div class="buttonContainer">' +
'									<div class="buttonRightContainer">' +
'										<input type="submit" id="forgot_password_submit" value="Send e-mail" />' +
'									</div>' +
'								</div>' +
'							</form>' +
'						</div>' +
'' +
'						<div id="forgotPasswordMessage" class="bubbleContent"></div>' +
'					</td>' +
'					<td class="bmr"></td>' +
'				</tr>' +
'				<tr>' +
'					<td class="bbl"></td>' +
'					<td class="bb"></td>' +
'					<td class="bbr"></td>' +
'				</tr>' +
'			</table>' +
'		    </div>');
});

