function getElement(name) {
	return document.getElementById(name);
}

function addClass(elementName, clsName) {
	var e = getElement(elementName);
	if(e) {
		removeClass(elementName, clsName);
		e.className = e.className + " " + clsName;
	}
}

function removeClass(elementName, clsName) {
	var e = getElement(elementName);
	if(e) {
		e.className = e.className.replace(clsName, "");
	}
}

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 + "/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 + "/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;
}

/* Form Help-text functions {{{  */

function enterHelpField(ev) {
	var field = this;
	if($(field).hasClass("fieldHelp")) {
		$(field).removeClass("fieldHelp");
		field.value = '';
		field.maxlength = field.oldmaxlength; // * re-set the old limit
		//$(field).unbind("blur");
	}
}
function exitHelpField(ev) {
	var field = this;
	if(field.value == '' || field.value == field.helptext) {
		$(field).addClass("fieldHelp");
		field.maxlength = field.oldmaxlength; // * no limit for help text
		field.value = field.helptext;
	}
}

function removeHelpTexts(){
	$("form.withHelpTexts input[helptext]").each(function() {
		if(this.value == this.helptext)
			this.value = '';
	});
}
/* }}} */


function showOverlay(class_prefix, id) {
	if(window.ENABLE_EFFECTS) {
		var fadeEmbedIn = function() {
			$(this)
				.show()
				.animate({ 'opacity': 1 }, 300, 'swing');
				
			$("#" + class_prefix + "_background_"+id)
				.show()
				.animate({ 'opacity': 0.85 }, 300, 'swing');
				
			$("#" + class_prefix + "_content_"+id)
				.css("padding-left", "20px")
				.show()
				.animate({ 'paddingLeft': "10px"}, { queue: false, duration: 300, easing: 'swing'  })
				.animate({ 'opacity': 1 }, 300, 'swing');
		};
		$("#" + class_prefix + "_background_" + id).fadeTo(1, 0);
		$("#" + class_prefix + "_" + id).fadeTo(1, 0, fadeEmbedIn);
	} else {
		$('#' + class_prefix + '_' + id).show();
		$('#' + class_prefix + '_background_' + id).css("height", "500px").css("width", "500px").show();
		$('#' + class_prefix + '_content_' + id).css("padding-left", "10px").show();
	}
	return false;
}

function hideEmbed(class_prefix, id) {
	if(window.ENABLE_EFFECTS) {
		$('#' + class_prefix + '_content_' + id)
			.animate({ 'paddingLeft': "0px"}, { queue: false, duration: 300 })
			.animate({ 'opacity': 0 }, 300, 'swing', function() { $(this).hide() });
		
		$('#' + class_prefix + '_' + id).animate({ 'opacity': 0 }, function() { $(this).hide() });
	} else {
		$('#' + class_prefix + '_background_' + id).hide();
		$('#' + class_prefix + '_content_' + id).hide();
		$('#' + class_prefix + '_' + 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();
}

function openLanguageSelector() {
	showBubbleContent("languageSelector");
	showBubble("languageSelector", $("#languageMenuLink"));
}

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);
	}
}

var helpBubbleTimer = null;
function showHelpBubble(element) {
	if(helpBubbleTimer != null) {
		clearTimeout(helpBubbleTimer);
	}
	
	helpBubbleTimer = setTimeout(function() {
		var helpBox = $(element).parent("p.field").next("div.helpBox");
		if(!$.browser.msie)
			helpBox.fadeIn(200);
		else
			helpBox.show();
	}, 700);
}

function hideHelpBubble(element) {
	$(element).parent("p.field").next("div.helpBox").hide();
}

/* ------------------------ */


$(document).ready(function() {
	// * Enable ability to custom style all input elements based on their type
	// * The equivalent CSS selectors doesn't work in IE 6 (and 7?)
	$("input[type=text]").add("input[type=password]").addClass("text");
	$("input[type=checkbox]").addClass("checkbox");
	$("input[type=radio]").addClass("radio");
	$("input[type=submit]").addClass("submit");
	$("input[type=button]").addClass("button");
	$("input[type=image]").addClass("image");
	$("input[type=file]").addClass("file");
	
	// * display help text
	$("form.withHelpTexts input[helptext]").each(function(){
		this.helptext = $(this).attr("helptext");
		this.oldmaxlength = $(this).attr("maxlength");
		$(this).focus(enterHelpField);
		$(this).blur(exitHelpField);
		$(this).blur();
	});
	$("form.withHelpTexts").submit(removeHelpTexts);
	
	// * widen stylability for form errors
	$(".fieldHasError").prev("label").addClass("labelHasError");
	
	hideBubble();
	
	$("form.withHelpTexts p.field :input").focus(function() { showHelpBubble(this); });
	$("form.withHelpTexts p.field :input").blur(function() { hideHelpBubble(this) });

    // Make the share links open in a popup window
    $("a.sharePopup").click(function() {
        url = $(this).attr("href");

        var w = 800;
        var h = 400;
        
        var left = (screen.width  / 2) - (w  / 2);
        var top  = (screen.height / 2) - (h  / 2);
        window.open(url, "pagegangster_share", 'width='+w+',height='+h+',scrollbars=yes,left='+left+',top='+top+",");

        return false;
    });
});


