var req, activecomment;
var selectedItem, action;
var getElement = document.getElementById;
function openBrWindow(theURL,winName,features) {window.open(theURL,winName,features);}
function viewImage(theURL,width,height) {
	if(screen.height < height) height = screen.height-100;
	openBrWindow(theURL,'preview','status=yes,scrollbars=yes,width='+width+',height='+height);
}
function emailReminder() {
	var setting = document.getElementById('reminder').checked;
	var url = "/lib/actions.php?action=emailReminder&setting=" + setting;
	getXMLDoc(url, 'GET', prefSet);
}
function prefSet(){if (req.readyState == 4) {if(req.status==200){/*NOTHING*/} else {alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");}}}
function reloadPage(viewby) {
	var query = window.location.search.substring(1);
	var query_string = '';
	if(query != "") {
		var parms = query.split('&');
		for (var i=0; i<parms.length; i++) {
			if(parms[i].indexOf('viewby') == -1) query_string += parms[i] + '&';
		}
	}
	query_string += 'viewby=' + viewby;
	
	window.location = location.pathname + '?' + query_string;
}
function digg() {
	var url   = encodeURIComponent(location.href);
	var title = encodeURIComponent(document.title);
	var description = (document.getElementById('item-description')) ? document.getElementById('item-description').innerHTML : null;
	var topic = "Offbeat+News";
	openBrWindow('http://digg.com/submit?phase=2&url='+ url + '&title=' + title + '&bodytext=' + description + '&topic=' +topic, 'digg', 'toolbar=no,width=700,height=400');
}
function delicious() {
	var url   = encodeURIComponent(location.href); 
	var title = encodeURIComponent(document.title);
	openBrWindow('http://del.icio.us/post?v=4&noui&jump=close&url='+url+'&title='+title, 'delicious', 'toolbar=no,width=700,height=400');
}
function browse() {
	var publisher = document.getElementById('browse_publisher').value;
	var month     = document.getElementById('browse_month').value;
	var year      = document.getElementById('browse_year').value;
	var url       = (publisher == "viewall") ? "" : publisher;
	url += "/" + year + "/" + month + "/00";
	window.location = url
}
function changeWeek(oldvalue) {
	var browse_month = document.getElementById('browse_month');
	if(!browse_month.options[browse_month.selectedIndex].disabled) {
		var month     = document.getElementById('browse_month').value;
		var year      = document.getElementById('browse_year').value;
		var url = "/lib/actions.php?action=changeWeek&y=" + year + "&m=" + month;
		getXMLDoc(url, 'GET', weekDone);
	} else {
		browse_month.selectedIndex = oldvalue;
	}
}
function weekDone() {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
			//alert(req.responseText);
			document.getElementById('weeks').innerHTML = req.responseText;
        } else {
	        alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");        	
        }
    }
}
function changeYear(oldvalue) {
	var select = document.getElementById('browse_year');
	var year   = select.value;
	var url    = "/lib/actions.php?action=updateYear&y=" + year;
	select.disabled = true;
	document.getElementById('browse_month').disabled = true;;
	getXMLDoc(url, 'GET', yearDone);
}
function yearDone() {
	if (req.readyState == 4) {
		// only if "OK"
		if (req.status == 200) {
			response   = req.responseXML.documentElement;
			var months = response.getElementsByTagName('months')[0].firstChild.data;
			var weeks  = response.getElementsByTagName('weeks')[0].firstChild.data;
			document.getElementById('months').innerHTML = months;
			document.getElementById('weeks').innerHTML = weeks;
		} else {
			alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");        	
		}
		document.getElementById('browse_year').disabled = false;
	}
}
function spam(id, div) {
	if(confirm('Are you sure you wish to flag this post as spam?')) {
		selectedItem = div;
		getXMLDoc("/lib/actions.php?action=flagSpam&id="+id, 'GET', flagged);
	}
}
function flag(id, div) {
	if(confirm('Are you sure you wish to flag this post as innappropriate?')) {
		selectedItem = div;
		getXMLDoc("/lib/actions.php?action=flagInappropriate&id="+id, 'GET', flagged);
	}
}
function flagged() {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
        	if(req.responseText == "true") {
        		alert('This item has been flagged for review, thank you.');
        		document.getElementById(selectedItem).style.display = 'none';
			}
        } else {
	        alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");        	
        }
    }
}
function bagIt(sku) {
	var url = "/lib/actions.php?action=bagIt&sku=" + sku;
	getXMLDoc(url, 'GET', ratingDone);
}
function burnIt(sku) {
	var url = "/lib/actions.php?action=burnIt&sku=" + sku;
	getXMLDoc(url, 'GET', ratingDone);
}
function ratingDone() {
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
        	if(req.responseText == "true") {
				document.getElementById("bagit").innerHTML = '<img src="/xtras/bagit_x.gif" width="90" height="18" />';
				document.getElementById("burnit").innerHTML = '<img src="/xtras/burnit_x.gif" width="90" height="18" />';
			}
        } else {
	        alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");        	
        }
    }
}
function postComments(id, sku, parent, resp) {
	if($('#'+id+' textarea').val() && $('#comment_title').val() && $('#comment_url').val()) {
		$('#'+id+' .submit').val('Sending Comment...');
		$('#'+id+' .submit').attr('disabled', true);
		$('#'+id+' .submit')[0].className = 'submit-disabled';
		$('#'+id+' textarea').attr('disabled', true);
		
		var vars = {};
		vars.action = 'postComments';
		vars.comment_title = $('#comment_title').val();
		vars.comment_url = $('#comment_url').val();
		vars.sku = sku;
		vars.comment = $('#'+id+' textarea').val();
		if(parent) vars.comment_parent = parent;
		if(resp) vars.comment_response = resp;
		
		$.ajax({
			type: 'GET',
			url: '/lib/actions.php',
			data: vars,
			dataType: 'xml',
			success: function(xml) {
				if($(xml).find('result').text() == 'true') {
					alert("Your comment has been posted!");
					$('#'+id+' .submit').val('Comment Posted!');
					$('#'+id+' .submit')[0].className = 'cancel';
				} else {
					error = $(xml).find('error').text();
					alert("An error has occured: "+error);
					$('#'+id+' .submit').val('ERROR');
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
					alert("Unable to Post your comments at this time. " + textStatus + '->' + errorThrown);
				}
			}
		);
	}
}
function reply(id, sku, parent, resp) {
	var comment = document.getElementById(id);
	var i = document.getElementsByTagName('textarea').length;
	var div = document.createElement('div');
	div.setAttribute('id', 'commentdiv'+i);
	div.setAttribute('class', 'spacer');
	var textarea = document.createElement('textarea');
	textarea.setAttribute('id', 'comment');
	textarea.setAttribute('name', 'comment');
	textarea.setAttribute('class', 'comment');
	textarea.setAttribute('onFocus', "this.className='comment-expanded'");
	div.appendChild(textarea);
	var btn   = document.createElement('div');
	btn.setAttribute('class', 'btn');
	var input = document.createElement('input');
	input.setAttribute('type', 'button');
	input.className = 'submit';
	input.setAttribute('id', 'comment_btn');
	input.setAttribute('value', 'Post Comment');
	input.setAttribute('onClick', 'postComments("commentdiv'+i+'", "'+sku+'", "'+parent+'", "'+resp+'");');
	btn.appendChild(input);
	div.appendChild(btn);
	var spacer = document.createElement('div');
	spacer.setAttribute('id', 'spacer');
	spacer.innerHTML = "&nbsp;";
	div.appendChild(spacer);
	comment.appendChild(div);
}
function addToPullList(sku, pubDate, item) {
	var vars = {action:'addToPullList', sku: sku, pubDate:pubDate};
	$(item).removeAttr('onclick');
	$(item).css('cursor', 'wait');
	$(item).find('img').fadeTo('fast', 0.33);
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'xml',
		success: function(xml) {
			if($(xml).find('pulllist')) {
				$(item).html('<img src="http://cdn.comixology.com/xtras/pulled.png" width="54" height="24" />');
				$(item).css('cursor', 'default');
				updatePullList(xml);
			} else {
				alert("Unable to pull at this time.\n" + xml);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Unable to pull at this time. " + textStatus + '->' + errorThrown);
			}
		}
	);
}
function removeFromPullList(sku, pubDate, item) {
	var vars = {action:'removeFromPullList', sku: sku, pubDate:pubDate};
	$(item).removeAttr('onclick');
	$(item).css('cursor', 'wait');
	$(item).find('img').fadeTo('fast', 0.33);
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'xml',
		success: function(xml) {
			if($(xml).find('pulllist')) {
				$(item).html('<img src="http://cdn.comixology.com/xtras/done.png" width="54" height="24" />');
				$(item).css('cursor', 'default');
				updatePullList(xml);
			} else {
				alert("Unable to pull at this time.\n" + xml);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Unable to pull at this time. " + textStatus + '->' + errorThrown);
			}
		}
	);
}
function updatePullList(xml) {
	if($('#pulllist')[0]) {
		createPullList(xml);
	} else if($('#total-count')) {
		var total    = $(xml).find('pulllist').attr('total');
		if(total == 0) total = '0.00';
		$('#total-count').html('$' + total);
	}
}
function loadPullList(pubDate) {
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'loadPullList',pubDate:pubDate},
		dataType: 'xml',
		success: function(xml) {
			createPullList(xml);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Unable to pull at this time. " + textStatus + '->' + errorThrown);
			}
		}
	);
}
function addElement(type, attributes) {
	var element = document.createElement(type);
	if(attributes != null) {
		for(var name in attributes) {
			if(name == 'clss') {
				element.setAttribute('class', attributes[name]);
			} else {
				element.setAttribute(name, attributes[name]);
			}
		}
	}
	return element;
}
function createPullList(xml) {
	var total = $(xml).find('pulllist').attr('total');
	if(total == 0) total = '0.00';
	var list     = document.getElementById('pulldiv');
	list.innerHTML = '';
	var pulllist = addElement('div', {id: 'pulllist'});
	list.appendChild(pulllist);
	var top      = addElement('div', {id: 'pull-top'});
	pulllist.appendChild(top);
	var div      = addElement('div', {id: 'total'});
	top.appendChild(div);
	/*------------------------------------------------------------------------*/
	var table    = addElement('table', {cellpadding: '0', cellspacing: '0', border: '0'});
	div.appendChild(table);
	var tr       = addElement('tr');
	table.appendChild(tr);
	var td       = addElement('td');
	tr.appendChild(td);
	var img      = addElement('img', {src: '/xtras/total-left.gif', width: '6', height: '18'});
	td.appendChild(img);
	var td       = addElement('td', {id: 'total-count'});
	var text     = document.createTextNode('$' + total);
	td.appendChild(text);
	tr.appendChild(td);
	var td       = addElement('td');
	tr.appendChild(td);
	var img      = addElement('img', {src: '/xtras/total-right.gif', width: '6', height: '18'});
	td.appendChild(img);
	/*------------------------------------------------------------------------*/
	var spacer   = addElement('div', {id: 'spacer'});
	spacer.innerHTML = '&nbsp;';
	div.appendChild(spacer);
	var content  = addElement('div', {id: 'pull-content'});
	pulllist.appendChild(content);
	var div      = addElement('div', {id: 'list'});
	content.appendChild(div);
	var table    = addElement('table', {cellpadding: '0', cellspacing: '0', border: '0', width: '100%'});
	div.appendChild(table);
	var tbody    = addElement('tbody', {id: 'pull-items'});
	table.appendChild(tbody);
	
	$(xml).find('item').each(function(i) {
		var sku   = $(this).attr("id");
		var title = $(this).attr("title");
		var price = $(this).attr("price");
		var tr    = addElement('tr', {bgcolor: (i%2==0) ? '#ffffff' : '#d4edf9'});
		tbody.appendChild(tr);
		var td    = addElement('td', {clss: 'pulllist'});
		td.innerHTML = '<a href="/sku/' + sku + '">' + title + '</a>';
		tr.appendChild(td);
		var td   = addElement('td', {clss: 'pulllist', style: 'text-align: right; border-left: 1px solid #666666; padding-right: 10px;', width: '50'});
		td.innerHTML = '$' + price;
		tr.appendChild(td);
	});
	var bottom   = addElement('div', {id: 'pull-bottom'});
	list.appendChild(bottom);
	var img      = addElement('img', {src: '/xtras/pulllist-bottom.gif', width: '470', height: '47'});
	bottom.appendChild(img);
}
function setcookie(key, value) {
	var date  = new Date();
	date.setTime(date.getTime()+(365*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	document.cookie = key + "="+value+expires+"; path=/";
}
function updateDiscount() {
	var newval = document.getElementById('discount').value;
	var oldval = document.getElementById('olddiscount').value;
	if(newval!=oldval) {
		var url = "/lib/actions.php?action=updateDiscount&discount=" + newval;
		getXMLDoc(url, 'GET', discountUpdated);
	}
}
function updateSalesTax() {
	var newval = document.getElementById('salestax').value;
	var oldval = document.getElementById('oldtax').value;
	if(newval!=oldval) {
		var url = "/lib/actions.php?action=updateSalesTax&tax=" + newval;
		getXMLDoc(url, 'GET', salesTaxUpdated);
	}
}
function discountUpdated(){if (req.readyState == 4) {if(req.status==200){document.getElementById('olddiscount').value=req.responseText;updateTotal();} else {alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");}}}
function salesTaxUpdated(){if (req.readyState == 4) {if(req.status==200){document.getElementById('oldtax').value=req.responseText;updateTotal();} else {alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");}}}
function updateTotal(){
	var subtotal = document.getElementById('subtotal').value;
	var discount = document.getElementById('discount').value;
	var salestax = document.getElementById('salestax').value;
	var a = subtotal * ((100-discount)*.01);
	var total = a + (a*(salestax*.01));
	document.getElementById('totaltd').innerHTML = '$' + total.toFixed(2);
}
function submitIt() {
	var results = document.getElementById('signup-results');
	var email = document.getElementById('email');
	if(!validEmail(email.value)) {
		email.style.backgroundColor = "#ffffcc";
		results.innerHTML = 'You must enter a valid Email Address';
		results.style.border = '4px solid #ff0000';
		return false;
	} else {
		email.style.backgroundColor = "#ffffff";
	}
	var usr = document.getElementById('usrnm');
	if(usr.value.length <= 4) {
		usr.style.backgroundColor = "#ffffcc";
		results.innerHTML = 'User Names must be 4 - 30 characters';
		results.style.border = '4px solid #ff0000';
		return false;
	} else {
		usr.style.backgroundColor = "#ffffff";
	}
	var passwd = document.getElementById('passwd');
	if(passwd.value.length <= 5) {
		results.innerHTML = 'Password must be 6 - 20 characters';
		passwd.style.backgroundColor = "#ffffcc";
		results.style.border = '4px solid #ff0000';
		return false;
	} else {
		passwd.style.backgroundColor = "#ffffff";
	}
	var passwd2 = document.getElementById('passwd2');
	if(passwd2.value.length <= 5) {
		results.innerHTML = 'Password must be 6 - 20 characters';
		passwd2.style.backgroundColor = "#ffffcc";
		results.style.border = '4px solid #ff0000';
		return false;
	} else {
		passwd2.style.backgroundColor = "#ffffff";
	}
	if(passwd.value != passwd2.value) {
		results.innerHTML = 'Passwords do not match';
		passwd.style.backgroundColor = "#ffffcc";
		passwd2.style.backgroundColor = "#ffffcc";
		results.style.border = '4px solid #ff0000';
		return false;
	}
	var country = document.getElementById('country');
	if(country.value == '---') {
		results.innerHTML = 'You must select a Country';
		results.style.border = '4px solid #ff0000';
		return false;
	}
	var postalcode = document.getElementById('postalcode');
	if(country.value == 'US' || country.value == 'GB' || country.value == 'CA') {
		if(postalcode.value.length < 5) {
			results.innerHTML = 'US, UK & Canadian residents must enter Postal Code';
			results.style.border = '4px solid #ff0000';
			return false;
		}
	}
	var male = document.getElementById('male');
	var female = document.getElementById('female');
	
	if(!male.checked && !female.checked) {
		results.innerHTML = 'You must specify your Gender';
		results.style.border = '4px solid #ff0000';
		return false;
	}
	var month = document.getElementById('month');
	var day   = document.getElementById('day');
	var year  = document.getElementById('year');
	if(month.value == "00" || day.value == "00" || year.value == "0000") {
		results.innerHTML = 'You must enter your Date of Birth';
		results.style.border = '4px solid #ff0000';
		return false;
	}
	var verification = document.getElementById('code');
	if(verification.value.length < 7) {
		results.innerHTML = 'Please verify your entry';
		verification.style.backgroundColor = "#ffffcc";
		results.style.border = '4px solid #ff0000';
		return false;
	} else {
		verification.style.backgroundColor = "#ffffff";
	}
	return true;
}
function usrnmAvail() {
	var usrnm = document.getElementById('usrnm').value;
	var url = '/lib/actions.php?action=checkUser&usr=' + usrnm;
	document.getElementById('results').innerHTML = '<b><i>Checking...</i></b>';
	document.getElementById('avail').disabled = true;
	getXMLDoc(url, 'GET', usrLoaded);
}
function usrLoaded() {
    // only if req shows "complete"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
        	if(req.responseText == "true") {
				document.getElementById('results').innerHTML = '<b>Username available.</b>';
			} else {
				document.getElementById('results').innerHTML = '<b>Username already taken.</b>';
			}
			document.getElementById('avail').disabled = false;
        } else {
	        alert("There was a problem retrieving the XML data:\n" + req.statusText + " "+ req.status + ")");
	        document.getElementById('avail').disabled = false;
        }
    }
}
function switchTab(tab, items) {
	var vars;
	var image = $('#related #tab').css('background-image');

	if(tab == "related" && $('#related #tab').attr('class') != 'related') {
		$('#related #tab').attr('class', 'related');
		
		vars = {action: 'fetchRelated', sku: items};
	} else if(tab == "additional" && $('#related #tab').attr('class') != 'additional') {
		$('#related #tab').attr('class', 'additional');

		vars = {action: 'fetchAdditional', c: items.c, d: items.d};
		//if(items.i) vars[i] = items.i;
	}
	
	
	$('#related-items').html('');
	$.ajax({
		type: 'GET',
		url: '/lib/actions.php',
		data: vars,
		success: function(html) {
			$('#related-items').html(html);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Unable to subscribe at this time. " + textStatus + '->' + errorThrown);
			}
		}
	);
}
function toggleDisplay(id) {
	var item = document.getElementById(id);
	
	if($('#'+id).css('display') == 'none') {	
		$('#'+id).fadeIn('normal')
	} else {
		$('#'+id).fadeOut('normal')
	}
}
function toggleSlide(id) {
	var item = document.getElementById(id);
	
	if($('#'+id).css('display') == 'none') {	
		$('#'+id).slideDown('normal')
	} else {
		$('#'+id).slideUp('normal')
	}
}
function subscribe(seriesid, sku, format) {
	if(!sku) sku = $('#product_id').val();
	var vars = {action:'subscribe', code: seriesid, sku: sku};
		vars[format] = true;
	$('#' + sku + ' #subscribe').removeAttr('onclick');
	$('#' + sku + ' #subscribe').css('cursor', 'wait');
	$('#' + sku + ' #subscribe').find('img').fadeTo('fast', 0.33);
	$('#' + sku + ' #btn').removeAttr('onclick');
	$('#' + sku + ' #btn').css('cursor', 'wait');
	$('#' + sku + ' #btn').find('img').fadeTo('fast', 0.33);
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		success: function(xml) {
			if($(xml).find('status').text() == 'success') {
				$('#' + sku + ' #subscribe').css('cursor', 'default');
				$('#' + sku + ' #subscribe').html('<a href="/subscriptions/?series='+seriesid+'#'+seriesid+'"><img src="http://cdn.comixology.com/v2/xtras/edit_sub.png" width="54" height="24" /></a>');
				if($('#' + sku + ' #btn').length > 0) {
					$('#' + sku + ' #btn').css('cursor', 'default');
					$('#' + sku + ' #btn').html('<img src="http://cdn.comixology.com/xtras/pulled.png" width="54" height="24" />');
				}
				jQuery.noticeAdd({
					text: $(xml).find('added').text() + ' items added to your pull list',
					stay: false
				});
			} else {
				alert("Unable to subscribe at this time.\n" + xml);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
				alert("Unable to subscribe at this time. " + textStatus + '->' + errorThrown);
			}
		}
	);
}
function subscribe2(code, sku) {
	$('#add').val('Adding...');
	$('#add').attr('disabled', 'true');
	$('#add')[0].className = 'submit-disabled';
	var variants = $('#variants')[0].checked ? 1 : 0;
	var reprints = $('#reprints')[0].checked ? 1 : 0;
	if(!sku) sku = $('#product_id').val();
	var vars = {action:'subscribe', code: code, variants: variants, reprints: reprints, sku: sku};
	var count = 0;
	$('#format0 input[@type="checkbox"]').each(function(i) {
		vars[this.name] = this.checked;
		count++;
	});
	if(count > 0) {
		$.ajax({
			type: 'POST',
			url: '/lib/actions.php',
			data: vars,
			success: function(xml) {
				if($(xml).find('status').text() == 'success') {
					$('#' + sku + ' #subscribe').html('<img src="http://cdn.comixology.com/xtras/done.png" width="54" height="24" />');
					closeSub();
				} else {
					alert("Unable to subscribe at this time.\n" + xml);
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
					alert("Unable to subscribe at this time. " + textStatus + '->' + errorThrown);
				}
			}
		);
	} else {
		alert("You haven't selected any formats");
		$('#add').val('Add');
		$('#add').attr('disabled', '');
	}
}
function updateSubscription(btn, seriesid, id) {
	btn.value = 'Updating...';
	btn.disabled = true;
	btn.className = 'submit-disabled';
	var variants = $('#variants').attr('checked') ? 1 : 0;
	var reprints = $('#reprints').attr('checked') ? 1 : 0;
	var vars = {action:'updateSubscription', seriesid: seriesid, variants: variants, reprints: reprints};
	var count = 0;
	$('#'+id+' input[@type="checkbox"]').each(function(i) {
		vars[this.name] = this.checked;
		count++;
	});
	if(count > 0) {
		$.ajax({
			type: 'POST',
			url: '/lib/actions.php',
			data: vars,
			dataType: 'json',
			success: function(obj) {
				if(obj.success) {
					$('#'+id+' #status').html('Your subscription has been updated. ' + obj.added + ' items added, ' + obj.deleted + ' items removed');
					btn.value = 'Update';
					btn.disabled = false;
					btn.className = 'submit';
					$('#'+id+' #status').css('display','');
					setTimeout(function() { $('#'+id+' #status').slideUp(); }, 2000);
				} else {
					$('#'+id+' #status').html("Unable to update your subscription at this time.\n" + obj.error);
					$('#'+id+' #status').css('display','');
					setTimeout(function() { $('#'+id+' #status').slideUp(); }, 2000);
				}
			}
		});
	} else {
		alert("You haven't selected any formats");
		btn.value = 'Update';
		btn.disabled = false;
	}
}
function viewSubPulls(seriesid) {
	if($('#sub-pulls').length > 0) $('#sub-pulls').remove();
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'getPulledSubItems', seriesid: seriesid},
		dataType: 'html',
		success: function(html) {
			$('body').append(html);
			$('#sub-pulls').jqm();
			$('#sub-pulls').jqmAddClose('.deleteButton');
			$('#sub-pulls').jqmShow();
		}
	});
}
function removeSubItem(sku) {
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'removeSubItem', sku: sku},
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#'+sku).remove();
				var i = 0;
				$('#sub-pulls tbody tr').each(function() {
					var c = i%2 == 0 ? 'normal' : 'hilight';
					$(this).attr('class', c);
					i++;
				});
			} else {
				alert(obj.error);
			}
		}
	});
}
function confirmDelete(id, seriesid) {
	$('#check'+id).fadeIn();
	$('#delete'+id).val('Confirm Delete');
	$('#delete'+id).removeAttr('onclick').click(function() {removeSubscription(id, seriesid);});
}
function confirmSubscription(id, seriesid) {
	$('#confirm'+id).val('Confirm Subscription');
	$('#confirm'+id).removeAttr('onclick').click(function() {acceptSubscription(id, seriesid);});
}
function declineSubscription(id, seriesid) {
	$('#delete'+id).val('Confirm Decline');
	$('#delete'+id).removeAttr('onclick').click(function() {refuseSubscription(id, seriesid);});
}
function acceptSubscription(id, seriesid) {
	$('#confirm'+id).val('Accepting...');
	$('#confirm'+id)[0].disabled = true;
	$('#confirm'+id)[0].className = 'submit-disabled';
	var variants = $('#variants')[0].checked ? 1 : 0;
	var reprints = $('#reprints')[0].checked ? 1 : 0;
	var vars = {action:'acceptSubscription', seriesid: seriesid, variants: variants, reprints: reprints};
	var count = 0;
	$('#filters'+id+' input[@type="checkbox"]').each(function(i) {
		vars[this.name] = this.checked;
		count++;
	});
	if(count > 0) {
		$.ajax({
			type: 'POST',
			url: '/lib/actions.php',
			data: vars,
			dataType: 'json',
			success: function(obj) {
				if(obj.success) {
					$('#sub'+id+' #btns').html(
						'<input type="button" class="submit" id="delete'+id+'" value="Delete" onclick="confirmDelete(\''+id+'\',\''+seriesid+'\');" /> '+
						'<input type="button" class="submit" id="update'+id+'" value="Update" onclick="updateSubscription(this,\''+id+'\',\'filters'+id+'\');" />'
					);
					$('#subscriptions').append($('#sub'+id));
					
					$('#subscriptions div').each(function(i) {
						if(this.id=='subscription') {
							var className = ((n+1)%2 == 0) ? 'hilight' : 'normal';
							this.className = className;
							n++;
						}
					});
				} else {
					$('#'+id+' #status').html("Unable to update your subscription at this time.\n" + obj.error);
					$('#'+id+' #status').css('display','');
					setTimeout(function() { $('#'+id+' #status').slideUp(); }, 1000);
				}
			}
		});
	} else {
		alert("You haven't selected any formats");
		$('#confirm'+id).val('Accept');
		$('#confirm'+id)[0].disabled = false;
		$('#confirm'+id)[0].className = 'submit';
	}
}
function refuseSubscription(id, seriesid) {

}
function removeSubscription(id, seriesid) {
	var remove = $('#remove'+id).attr('checked');
	var data = {action: 'unsubscribe', code: seriesid, remove: remove};
	$('#delete'+id).val('Deleting...');
	$('#delete'+id).attr('disabled', 'true');
	$('#update'+id).attr('disabled', 'true');
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: data,
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#sub'+id).remove();
				var n = 0;
				$('#subscriptions div').each(function(i) {
					if(this.id=='subscription') {
						var className = ((n+1)%2 == 0) ? 'hilight' : 'normal';
						this.className = className;
						n++;
					}
				});
			} else {
				alert("Unable to update your subscription at this time.\n" + obj.error);
				$('#delete'+id).val('Confirm Delete');
				$('#delete'+id).attr('disabled', '');
				$('#update'+id).attr('disabled', '');
			}
		}
	});
}
function loadSub(seriesid, sku) {
	//if($('#recommendations')) $('#recommendations').css('display', 'none');
	$('body').append('<div id="module"><div class="progress">Loading...</div></div>');
	
	$('#module').jqm();
	$('#module').jqmShow();
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'getSub', seriesid: seriesid, sku: sku},
		success: function(html) {
			$('#module').html(html);
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("There was a problem retrieving the XML data:\n" + textStatus + " "+ errorThrown + ")");     
		}
	});

}
function closeSub() {
	$('#module').fadeOut('fast', function() {$('#module').jqmHide();/*if($('#recommendations')) $('#recommendations').css('display', '');*/});
}
function checkAll(id) {
	$('#'+id+' input[@type="checkbox"]').each(function(i) {
		if(!this.disabled) this.checked = true;
	});
}
function uncheckAll(id) {
	$('#'+id+' input[@type="checkbox"]').each(function(i) {
		if(!this.disabled) this.checked = false;
	});
}
function validEmail(email) {
	invalidChars = " /:,;"
	if (email == "") return false;
	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) {
			return false;
		}
	}
	atPos = email.indexOf("@",1);
	if (atPos == -1) return false;
	if (email.indexOf("@",atPos+1) != -1) return false;
	periodPos = email.indexOf(".",atPos);
	if (periodPos == -1) return false;
	if (periodPos+3 > email.length)	return false;
	return true;
}
function submitForm() {
	var submit      = document.getElementById('submit');
	submit.value    = 'Processing...';
	submit.disabled = true;
	var send        = true;
	var error       = "Following required fields are missing:\n";
	var name        = document.getElementById('name');
	if(name.value == "") {
		error += "Your Name\n";
		send = false;
		if(name!=null) name.style.backgroundColor = "#ffffcc"
	} else {
		name.style.backgroundColor = "#FFFFFF"
	}
	var comments = document.getElementById('comments');
	if(comments.value == "") {
		error += "Your Comments\n";
		send = false;
		comments.style.backgroundColor = "#ffffcc"
	} else {
		comments.style.backgroundColor = "#FFFFFF"
	}
	var email = document.getElementById('email');
	if(email != null) {
		if(!validEmail(document.getElementById('email').value)) {
			error += "Email\n";
			send = false;
			document.getElementById('email').style.backgroundColor = "#ffffcc"
		} else {
			document.getElementById('email').style.backgroundColor = "#FFFFFF"
		}
	}
	if(send) {
		document.getElementById('MAILFORM').submit();
	} else {
		alert(error);
		submit.value    = 'Submit Message';
		submit.disabled = false;
	}
}
function validEmail(email) {
	invalidChars = " /:,;"
	if (email == "") {
		return false
	}
	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (email.indexOf(badChar,0) > -1) {
			return false
		}
	}
	atPos = email.indexOf("@",1)
	if (atPos == -1) {
		return false
	}
	if (email.indexOf("@",atPos+1) != -1) {	
		return false
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {
		return false
	}
	if (periodPos+3 > email.length)	{
		return false
	}
	return true
}
function testPassword(id) {
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");
	var pwd = $('#'+id).val();
	/*
	if (pwd.length==0) {
		$('#strength').html('Type Password');
	} else 
	*/
	if (false == enoughRegex.test(pwd)) {
		$('#strength').html('Too Short');
	} else if (strongRegex.test(pwd)) {
		$('#strength').html('Password strength: <span style="color:green;font-weight:bold;">Strong</span>');
	} else if (mediumRegex.test(pwd)) {
		$('#strength').html('Password strength: <span style="color:orange;font-weight:bold;">Medium</span>');
	} else { 
		$('#strength').html('Password strength: <span style="color:red;font-weight:bold;">Weak</span>');
	}
}
function emailUpdates() {
	if($('#email').val() && validEmail($('#email').val())) {
		$('#status').html('Sending...');
		$('#status').css('display', '');
		$.ajax({
			type: 'POST',
			url: '/lib/actions.php',
			data: {action:'emailUpdates', email: $('#email').val()},
			dataType: 'xml',
			success: function(xml) {
				if($(xml).find('success').text() == 'true') {
					$('#status').html('You have successfully signed up.');
				} else {
					$('#status').html($(xml).find('error').text());
				}
				$('#status').css('display', '');
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("There was a problem retrieving the XML data:\n" + textStatus + " "+ errorThrown + ")");     
			}
		});
	} else {
		$('#status').html('Email address invalid.');
		$('#status').css('display', '');
	}
}
function clearField(id) {
	$('#'+id).val('');
	$('#'+id).css('color','#000');
}
function getURL(url, target) {
	if(target) {
		
	} else {
		window.location=url;
	}
}
function popUpWindow(sku, page_num) {
	if($('#popup').length > 0) $('#popup').remove();
	var vars = {action:'loadImage', sku:sku};
	if(page_num || page_num ===0) vars.page_num = page_num;
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'html',
		success: function(html) {
			$('body').append(html);
			$('#popup').jqm();
			$('#popup').jqmShow();
			$(document).keydown( function( e ) { 
				if( e.which == 27) {
					$("#popup").jqmHide();
					$(document).keydown(null);
					$('#popup').remove();
				}
			});
		}
	});	
}
function popUpWindow2(id) {
	if($('#popup').length > 0) $('#popup').remove();
	var vars = {action:'loadDigitalImage', item_id:id};
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'html',
		success: function(html) {
			$('body').append(html);
			$('#popup').jqm();
			$('#popup').jqmShow();
			$(document).keydown( function( e ) { 
				if( e.which == 27) {
					$("#popup").jqmHide();
					$(document).keydown(null);
					$('#popup').remove();
				}
			});
		}
	});	
}
function viewAgreement(store_id) {
	if($('#popup').length > 0) $('#popup').remove();
	var vars = {action:'viewAgreement', store_id:store_id};
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'html',
		success: function(html) {
			//$('body').append(html);
			/* IE Fix */
			var popup = document.createElement('div');
			document.body.appendChild(popup);
			popup.innerHTML = html;
			/* IE Fix */
			$('#popup').jqm();
			$('#popup').jqmShow();
			$(document).keydown( function( e ) { 
				if( e.which == 27) {
					$("#popup").jqmHide();
					$(document).keydown(null);
					$('#popup').remove();
				}
			});
		}
	});	
}
function acceptAgreement(store_id) {
	var fname = $('#fname').val();
	var lname = $('#lname').val();
	var phone = $('#phone').val();
	if(fname && lname &&phone && fname != '' && lname != '' && phone.length > 7) {
		$('#retail_accept').val('Accepting...');
		$('#retail_accept').toggleClass('submit-disabled');
		$('#retail_accept').attr('disabled', true);
		$('#retail_cancel').attr('disabled', true);
		var vars = {action:'connectUserToRetailer', store_id:store_id, fname: fname, lname: lname, phone: phone};
		$.ajax({
			type: 'POST',
			url: '/lib/actions.php',
			data: vars,
			dataType: 'json',
			success: function(obj) {
				if(obj.success) {
					$('#agreement').html(obj.html);
					$('#retail_connection #body').html('You are connected to ' + obj.store_name + '.');
					setTimeout(declineAgreement, 1500);
				} else {
					$('#popup #status').html(obj.error);
					$('#popup #status').css('display', '');
				}
			}
		});	
	} else {
		$('#popup #status').html('Missing Required Fields');
		$('#popup #status').css('display', '');
		$('#fname').css('backgroundColor', '#ffffcc');
		$('#lname').css('backgroundColor', '#ffffcc');
	}
}
function disconnectUser() {
	$('#retailer #submit').val('Disconnecting...');
	$('#retailer #submit').toggleClass('submit_sm-disabled');
	$('#retailer #submit').attr('disabled', true);
	$('#retailer #cancel').attr('disabled', true);
	var vars = {action:'disconnectUserFromRetailer'};
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#retailer #status').html('You have been successfully disconnected');
			} else {
				$('#retailer #status').html(obj.error);
			}
			setTimeout($('#retailer').fadeOut(), 1500);
		}
	});
}
function declineAgreement() {
	$("#popup").jqmHide();
	$(document).keydown(null);
	$('#popup').remove();
}
function alertWin() {
	$('body').append('<div id="module"><div class="progress">Loading...</div></div>');
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'getAlert'},
		success: function(html) {
			$('#module').html(html);
			$('#module').jqm();
			$('#module').jqmShow();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			alert("There was a problem retrieving the XML data:\n" + textStatus + " "+ errorThrown + ")");     
		}
	});
}
function viewIssue(issue_id) {
	$('#webcomic').append('<div id="ComicViewer"><div id="flash"></div></div>');
	swfobject.embedSWF("http://images.comixology.net/flash/ComicViewer.swf", "flash", "800", "600", "10.0.0", '/xtras/expressinstall.swf', {issue_id:issue_id}, {allowScriptAccess: 'always', allowFullScreen: true});
	$('#ComicViewer').jqm();
	$('#ComicViewer').jqmShow();
	$(document).keydown( function( e ) { 
		if( e.which == 27) {
			$("#ComicViewer").jqmHide();
			$(document).keydown(null);
			$('#ComicViewer').remove();
		}
	});
}
function getXMLDoc(url, method, funct, vars) {
	req = null
	if(window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
	}
	//req = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	if(req!=null) {
		req.onreadystatechange = funct;
		//req.setContentType("text/xml");
		//req.overrideMimeType("text/xml");
		req.open(method, url, true);
		req.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');
		req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		req.send(vars);
	} else {
		alert("Problems with XMLHTTP");
	}
}
function rateDigitalItem(value, item_id) {
	if(!value) value = 0;
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'rateDigitalItem',rating:value,item_id:item_id},
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#count').html(obj.count);
				$('.score').css('display', 'none');
				$('.score').html(obj.rating);
				$('.score').fadeIn();
			} else {
				alert(obj.error);
			}
		}
	});
}
function rateRetailer(value, store_id) {
	if(!value) value = 0;
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'rateRetailer',rating:value,store_id:store_id},
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#count').html(obj.count);
				$('.score').css('display', 'none');
				$('.score').html(obj.rating);
				$('.score').fadeIn();
			} else {
				alert(obj.error);
			}
		}
	});
}
function rateSeries(value, seriesid) {
	if(!value) value = 0;
	$.ajax({
		type: 'POST',
		url: '/lib/actions.php',
		data: {action:'rateSeries',rating:value,seriesid:seriesid},
		dataType: 'json',
		success: function(obj) {
			if(obj.success) {
				$('#count').html(obj.count);
				$('.score').css('display', 'none');
				$('.score').html(obj.rating);
				$('.score').fadeIn();
			} else {
				alert(obj.error);
			}
		}
	});
}
this.tooltip = function(){	
	xOffset = 10;
	yOffset = 20;		
	$("a.tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};
$(document).ready(function(){
	tooltip();
});
function clean(id) {
	var text = document.getElementById(id).value;
	var newtext = "";
	for(var i = 0; i < text.length; i++ ) {
		switch(text.charCodeAt(i)) {
		case(8217) : newtext += "'"; break;
		case(8220) : newtext += '"'; break;
		case(8221) : newtext += '"'; break;
		default : if(text.charCodeAt(i) > 160) { newtext += '&#' + text.charCodeAt(i) + ';'; } else { newtext += text.charAt(i); }
		}
	}
	document.getElementById(id).value = newtext;
	return true;
}
function switchApps(app) {
	if(app == 'iphone') {
		$('#iphone').fadeIn();
		$('#iphone2').css('display', 'none');
		$('#iphone3').css('display', 'none');
	} else if(app == 'iphone3') {
		$('#iphone3').fadeIn();
		$('#iphone').css('display', 'none');
		$('#iphone2').css('display', 'none');
	} else {
		$('#iphone2').fadeIn();
		$('#iphone').css('display', 'none');
		$('#iphone3').css('display', 'none');
	}
}
function loadDigitalPreview(id) {
	if($('#popup').length > 0) $('#popup').remove();
	var vars = {action:'loadDigitalPreview', id:id};
	$.ajax({
		type: 'GET',
		url: '/lib/actions.php',
		data: vars,
		dataType: 'html',
		success: function(html) {
			$('body').append(html);
			$('#popup').jqm();
			$('#popup').jqmShow();
			$(document).keydown( function( e ) { 
				if( e.which == 27) {
					$("#popup").jqmHide();
					$(document).keydown(null);
					$('#popup').remove();
				}
			});
		}
	});	
}
function closePreviewWindow() {
	$("#popup").jqmHide();
	$(document).keydown(null);
	$('#popup').remove();
}