var httpObject = null;

var loading_box = $('<div class="loading_box"></div>');
$(document).ready(function(){
	$('#content').append(loading_box);
})


function getXMLHTTPObject() {
	var ajaxRequest = null;  // The variable that makes Ajax possible!
    try {
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {
            try {
		        ajaxRequest = new XMLHttpRequest();
            } 
            catch (e) {
                alert("Your browser doesn't support AJAX!");
            }
        }
    }
	return ajaxRequest;
}

function addCategories(increment){
	var next_category = (increment-1);
	$('select[name=category'+ next_category +']').parent().clone().appendTo('#category').attr({'id':'category'+increment});
	$('#category'+increment+' '+'select').attr('name','category'+increment);
	$('#category'+increment+' '+'select').val('0');
	$('#category'+increment+' '+'label').html('');
	$('#category'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_c').value = increment;
}

function addDesigner(increment){
	var next_designer = (increment-1);
	$('select[name=designer'+ next_designer +']').parent().clone().appendTo('#designer').attr({'id':'designer'+increment});
	$('#designer'+increment+' '+'select').attr('name','designer'+increment);
	$('#designer'+increment+' '+'select').val('0');
	$('#designer'+increment+' '+'label').html('');
	$('#designer'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_d').value = increment;
}

function addCategoriesSwap(increment){
	var next_category = (increment-1);
	$('select[name=category_swap'+ next_category +']').parent().clone().appendTo('#category_swap').attr({'id':'category_swap'+increment});
	$('#category_swap'+increment+' '+'select').attr('name','category_swap'+increment);
	$('#category_swap'+increment+' '+'select').val('0');
	$('#category_swap'+increment+' '+'label').html('&nbsp;');
	$('#category_swap'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_cs').value = increment;
}

function addDesignerSwap(increment){
	var next_designer = (increment-1);
	$('select[name=designer_swap'+ next_designer +']').parent().clone().appendTo('#designer_swap').attr({'id':'designer_swap'+increment});
	$('#designer_swap'+increment+' '+'select').attr('name','designer_swap'+increment);
	$('#designer_swap'+increment+' '+'select').val('0');
	$('#designer_swap'+increment+' '+'label').html('&nbsp;');
	$('#designer_swap'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_ds').value = increment;
}

function addLifeStyle(increment){
	var next_life_style = (increment-1);
	$('select[name=life_style'+ next_life_style +']').parent().clone().appendTo('#lifeStyle').attr({'id':'life_style'+increment});
	$('#life_style'+increment+' '+'select').attr('name','life_style'+increment);
	$('#life_style'+increment+' '+'select').val('0');
	$('#life_style'+increment+' '+'label').html('');
	$('#life_style'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_l').value = increment;
}

function addTrend(increment){
	var next_trend = (increment-1);
	$('select[name=trend'+ next_trend +']').parent().clone().appendTo('#trend').attr({'id':'trend'+increment});
	$('#trend'+increment+' '+'select').attr('name','trend'+increment);
	$('#trend'+increment+' '+'select').val('0');
	$('#trend'+increment+' '+'label').html('');
	$('#trend'+increment+' '+'a').remove();

	increment++;
	document.getElementById('increment_t').value = increment;
}

function validItemAdd(){
	if($('input[name=title]').val() == ""){
		$('.errorTitle').html('Title is required');
	}else{
		document.uploadSimple.submit();
	}
	
}

function validateAccountForm(){
	var $i = 0;
	$(".validate").each(function(){
		if($(this).val() == "" || $(this).val() == "0"){
			$(this).nextAll('.javascriptError:first').show();
			$i++;
		}else{
			$(this).nextAll('.javascriptError:first').hide();
		}
		if($(this).is(':checkbox')){
			if($(this).is(':checked')){
				$(this).nextAll('.javascriptError:first').hide();
			}else{
				$(this).nextAll('.javascriptError:first').show();
				$i++;
			}
		}
	});
	if($i == 0){
		
		return true;
	}else{
		return false;
	}
}

function addToCart(item_id) {
	httpObject = getXMLHTTPObject();
	var operation = $('input:radio:checked[name=cart_operation]').val();
	if(!operation){
		alert('Please choose an operation!');
		return false;
	}
	params = 'item_id=' + encodeURIComponent(item_id)+'&operation=' + operation;
	
	if (operation == 'swap') {
		popupSwap(item_id);
	}
	else {
		if (httpObject != null) {
			loading_box.show();
			httpObject.open('POST', site_url + '/ajax/add_to_cart/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if (httpObject.responseText == "") {
						popupCart();
					}else{
						if(confirm('Please log in or register to make a transaction.')){
							window.location = '/login';
						} else {}	
					}
				}
			};
			httpObject.send(params);
		}
	}
}

function checkAndaddToCart(item_id, action){
	if(action == 'borrow'){
		$('#action_buy').attr('checked', '');
		$('#action_swap').attr('checked', '');
	} else {
		$('#action_'+action).attr('checked', 'checked');
	}
	addToCart(item_id);
}

function popupSwap(item_id) {	
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/get_swap/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		
		if (httpObject.responseText == 2) {
			if(confirm('Please log in or register to make a transaction.')){
				window.location = '/login';
			} else {}
      // memberPopup();
		  return false;
		} /*else if(httpObject.responseText != 1){
			$('.errorBid').html(httpObject.responseText);
			return false;
		}*/
		
		
		
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			
			var linkPosition = $('#header-shopping-cart-link').offset();
			$('#shopping-cart-popup').css('left', linkPosition.left + $('#header-shopping-cart-link').width() - $('#shopping-cart-popup').width() + 4);
			$('#shopping-cart-popup').css('top', linkPosition.top + $('#header-shopping-cart-link').height());
			
			$('#shopping-cart-popup').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
			$('#continue_link').bind('click', function() {
				return commitSwapStep1();
			});
			$('.qty input').each(function() {
				$(this).bind('blur', function() {
					var theID = this.id.replace('qty_', '');
					checkStock(theID, this.value);
				});
			});
			Custom.init();
		}
	};
	httpObject.send('requested_item_id=' + encodeURIComponent(item_id));
}

function checkStock(id, quantity) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + 'ajax/check_stock/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			if (httpObject.responseText != '') {
				alert(httpObject.responseText);
				$('#qty_' + id).focus().select();
			}
		}
	};
	httpObject.send('item_id=' + encodeURIComponent(id) + '&qty=' + encodeURIComponent(quantity));
}

function popupCauseSuggestion() {
	httpObject = getXMLHTTPObject();
	httpObject.open('GET', site_url + '/ajax/cause_suggestion', true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', '158px').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				return submitCauseSuggestion();
			});
			Custom.init();
		}
	};
	httpObject.send(null);
}

function submitCauseSuggestion() {
	var email = $('.suggest-cause-right input#email').val();
	var message = $('.suggest-cause-right textarea#message').val();
	var addToGuestlist = $('.suggest-cause-right input#guestlist-chk').is(':checked') ? '1' : '0';
	
	if (email == '' || message == '') {
		alert('E-mail and message fields are mandatory !');
		return false;
	}
	var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
	if (!pattern.test(email)) {
		alert('Please enter a valid E-mail address !');
		$('.suggest-cause-right input#email').select().focus();
		return false;
	}
	
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/submit_suggest_cause/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			eval('responseObj = ' + httpObject.responseText);
			alert(responseObj.message);
			if (responseObj.status === 0) {
				hideCart();
			}
		}
	}
	httpObject.send('email=' + encodeURIComponent(email) + '&message=' + encodeURIComponent(message) + '&add_to_guestlist=' + encodeURIComponent(addToGuestlist));
}

function commitSwapStep1() {
	var checkedIDs = getCheckedBoxes();
	if (checkedIDs[0].length == 0) {
		alert('You must choose at least one item to swap with !');
		return false;
	}
	
	
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/email_swap/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				$('#continue_link').unbind('click');
				return commitSwapStep2();
			});
			$('#cancel_link').bind('click', hideCart);
			Custom.init();
		}
	};
	httpObject.send('req_id=' + encodeURIComponent($('#req_id').val()) + '&suggest_id[]=' + checkedIDs[0].join('&suggest_id[]=') + '&suggest_qty[]=' + checkedIDs[1].join('&suggest_qty[]='));
}

function commitSwapStep2() {
	var suggestIDs = new Array();
	var suggestQtys = new Array();
	
	$(".suggest_ids").each(function() {
		suggestIDs[suggestIDs.length] = this.value;
		suggestQtys[suggestQtys.length] = $('#qty_' + this.value).val();
	});
	
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/submit_swap/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			var parts = httpObject.responseText.split('::');
			alert(parts[1]);
			if (parts[0] == '0') {
				document.location.href = site_url + 'account/swap_requests';
			}
		}
	};
	var queryString = 'req_id=' + encodeURIComponent($('#req_id').val()) + '&suggest_id[]=' + suggestIDs.join('&suggest_id[]=') + '&suggest_qty[]=' + suggestQtys.join('&suggest_qty[]=');
	if ($('#send_me_copy').is(':checked')) {
		queryString += '&send_me_copy=y';
	}
	httpObject.send(queryString);
}

function getCheckedBoxes() {
	var quantities = new Array();
	var checkedIDs = new Array();
	$('.swap_select:checked').each(function() {
		checkedIDs[checkedIDs.length] = this.value;
		quantities[quantities.length] = $('#qty_' + this.value).val();
	});
	return [checkedIDs, quantities];
}

function popupCart() {
	if (httpObject.readyState == 4) {
		httpObject = getXMLHTTPObject();
		httpObject.open('GET', site_url + '/ajax/get_cart/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.onreadystatechange = function() {
			
			if (httpObject.readyState == 4) {
				$('#shopping-cart-popup-content').html(httpObject.responseText);
				$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
				$('#lightbox_bg').show();
				var linkPosition = $('#header-shopping-cart-link').offset();
				$('#shopping-cart-popup').css('left', linkPosition.left + $('#header-shopping-cart-link').width() - $('#shopping-cart-popup').width() + 4);
				$('#shopping-cart-popup').css('top', linkPosition.top + $('#header-shopping-cart-link').height());
				
				$('#shopping-cart-popup').fadeIn('fast');
				$('html, body').animate({scrollTop: '0'}, 'slow');
				/*$('#item-left, #item-right, #sidebar-right').fadeTo('slow', 0.2, function() {
					$('#shopping-cart-popup').fadeIn('slow');
					$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
			    });*/
				loading_box.hide();
			}
		};
		httpObject.send(null);
	}
}

function addToWishlist(item_id, page) {
	httpObject = getXMLHTTPObject();
	
	params = 'item_id=' + encodeURIComponent(item_id) + '&page=' + encodeURIComponent(page);
	
	if (httpObject != null) {
		httpObject.open('POST', site_url + '/ajax/add_to_wishlist/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				
				alert(httpObject.responseText);
				if(page = "item_details"){
					window.location.reload();
				}	
			}
		};
		httpObject.send(params);
	}
}

function moveToWishlist(item_id, page){
	
	httpObject = getXMLHTTPObject();
	
	params = 'item_id=' + encodeURIComponent(item_id) + '&page=' + encodeURIComponent(page);
	
	if (httpObject != null) {
		httpObject.open('POST', site_url + '/ajax/move_to_wishlist/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				
				if (page == 'item_details') {
					if (httpObject.responseText == "This item is already in your wishlist !" || httpObject.responseText == 'You need to log into your account to add items to you wishlist.') {
						alert(httpObject.responseText);
					}
					else {
						if (httpObject.responseText == 'no product') {
							alert('You have successfully moved this item to your Wishlist');
							hideCart();
						}else{
							alert('You have successfully moved this item to your Wishlist');
							$('#shopping-cart-popup-content').html(httpObject.responseText);
							$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
						}
						
					}
				}else{
					alert('You have successfully moved this item to your Wishlist');
					$('#cart').html(httpObject.responseText);
					window.location.reload();
				}
			}
		};
		httpObject.send(params);
	}
	
}

function removeFromCart(item_id,page){
	httpObject = getXMLHTTPObject();
	
	params = 'item_id=' + encodeURIComponent(item_id) + '&page=' + encodeURIComponent(page);
	if (confirm('Remove item from cart?')) {
		if (httpObject != null) {
			httpObject.open('POST', site_url + '/ajax/remove_from_cart/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if (page == 'item_details') {
						if (httpObject.responseText == 'no product') {
							hideCart();
						}else{
							$('#shopping-cart-popup-content').html(httpObject.responseText);
							$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
						}
					}else{
						//$('#cart').html(httpObject.responseText);
						window.location.reload();
					}
				}
			};
			httpObject.send(params);
		}
	}
}

function removeFromCartAutomatic(item_id){
	httpObject = getXMLHTTPObject();
	
	params = 'item_id=' + encodeURIComponent(item_id);

	if (httpObject != null) {
		httpObject.open('POST', site_url + '/ajax/remove_from_cart/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				window.location.reload();
			}
		};
		httpObject.send(params);
	}

}

function removeFromWishlist(item_id, reload){
	httpObject = getXMLHTTPObject();	
	params = 'item_id=' + encodeURIComponent(item_id);
	if (confirm('Remove item from wishlist?')) {
		$("#wishlist_item_box_id_"+item_id).hide();
		if (httpObject != null) {
			httpObject.open('POST', site_url + 'ajax/remove_from_wishlist/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if (reload != 1) {
						$('#wishlist').html(httpObject.responseText);
					}else{
						window.location.reload();
					}
				}
			};
			httpObject.send(params);
		}
	}
}


function placeBid(item_id, amount) {
	httpObject = getXMLHTTPObject();
	$("#place_bid").unbind('click');
	params = 'item_id=' + encodeURIComponent(item_id) + '&amount=' + encodeURIComponent(amount);
	if (httpObject != null) {
		httpObject.open('POST', site_url + 'ajax/place_bid/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 1){
					$('#amount').val('');
					//document.bidForm.submit();
					//window.location.reload();
					//redirect to celebrity item page
					alert('Thank you for bidding!');
					document.location.href = site_url + 'celebrity_closet';
				} else if (httpObject.responseText == 2) {
				  window.location = '/login';
          // memberPopup();
				  return false;
				}else{
					$('.errorBid').html(httpObject.responseText);
					return false;
				}
			}
		};
		httpObject.send(params);
	}
}


function previewMailYahoo(){
	$('#email-preview').show('slow');
	$('html, body').animate({scrollTop:0}, 'slow');
	$(".confirm-button").append('<input type="hidden" value="yahoo" name="form" />');
	return false;
}

function previewMailRest(){
	$('#email-preview').show('slow');
	$('html, body').animate({scrollTop:0}, 'slow');
	$(".confirm-button").append('<input type="hidden" value="rest" name="form" />');
	return false;
}


function hideCart() {
	/*$('#item-left, #item-right').fadeTo('fast', 1, function() {
	 $('#sidebar-right').fadeTo('fast', 0.5);
	 //$('html, body').animate({scrollTop: $('#content').height()}, 'slow');
	 });*/
	$('#shopping-cart-popup').fadeOut('fast', function() {
		$("#lightbox_bg").hide();
	});
	$("#lightbox_bg").hide();
}


/* function to edit address */

function editAddress(id, page) {
	$.ajax({
		type: "POST",
		url: site_url + "ajax/edit_address/" + Math.random(10000),
		data: "id=" + id + "&page=" + page,
		success: function(msg) {
			$('.checkout-edit-address').html(msg);
			$('.checkout-edit-address').show();
			$('.checkout-add-address').hide();
		}
	});
}

function editFromAddress(id) {
	$.ajax({
		type: "POST",
		url: site_url + "ajax/edit_from_address/" + Math.random(10000),
		data: "id=" + id,
		success: function(msg) {
			document.getElementById('from_address'+id).innerHTML = msg;
		}
	});
}

function deleteAddress(id){
	if(confirm('Delete the address?')){
		$.ajax({
			type: "POST",
			url: site_url + "ajax/delete_address/" + Math.random(10000),
			data: "id=" + id,
			success: function(msg) {
				window.location.reload();
			}
		});
	}
}

function generateURL(form, id){
	var form_name = form;
	$.ajax({
		type: "POST",
		url: site_url + "ajax/generate_return/" + Math.random(10000),
		data: "id=" + id,
		success: function(msg) {
			document.getElementById('return_' + id).value = msg;
			$('#'+form_name).submit();
		}
	});
}

function populateCities(state, city){
	$.ajax({
		type: "POST",
		url: site_url + "ajax/populate_cities/" + Math.random(10000),
		data: "state=" + state + "&city=" + city,
		success: function(msg) {
			$('select[name=city]').html(msg);
			$('select[name=e_city]').html(msg);
		}
	});
}

function populateFromCities(state, city){
	$.ajax({
		type: "POST",
		url: site_url + "ajax/populate_cities/" + Math.random(10000),
		data: "state=" + state + "&city=" + city,
		success: function(msg) {
			$('select[name=from_city]').html(msg);
		}
	});
}

function addToUserWishlist(){
	var category = $('select[name=wishlist_category] option:selected').val();
	var designer = $('select[name=wishlist_designer] option:selected').val(); 
	var text = $("input[name=looking_for_text]").val();
	if (category == "" && designer == "" && text == "") {
		alert('Please select a category or a designer or write a text');
	}
	else {
		$.ajax({
			type: "POST",
			url: site_url + "ajax/insert_into_user_wishlist/" + Math.random(10000),
			data: "category=" + category + "&designer=" + designer + "&text=" + text,
			success: function(msg) {
				$('.wishlist-right ul').html(msg);
			}
		});
	}
}

function updateCart(cart_item_id, quantity, item_id, popup){
	if (quantity != 0 && !isNaN(quantity) && Math.floor(quantity).toString() == quantity.toString()) {
		$.ajax({
			type: "POST",
			url: site_url + "ajax/update_cart_quantity/" + Math.random(10000),
			data: "cart_item_id=" + cart_item_id + "&quantity=" + quantity + "&item_id=" + item_id + "&popup=" + popup,
			success: function(msg) {
				if(msg == 0){
					if(confirm('The item was bought! Add the item to wishlist?')){
						moveToWishlist(item_id, '');
					}else{
						removeFromCartAutomatic(cart_item_id, '')
					}	
				}
				if(msg == 1){
					alert('The quantity is bigger than the stock');
				}else{
					if (msg != 2) {
						$('#shopping-cart-popup-content').html(msg);
						$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
					}else{
						window.location.reload();
					}
				}
			}
		});
	}else{
		alert('The quantity must be a interger value and > 0');
	}
}

function updateWholeCart(url){
	query_string = new Array();
	var test = "";
	x = 0;
	$("input[name=quantity]").each(function(){
			var item_id = $(this).attr('id').substr(4); 
         	arrQty = this.value;
			arrItem = item_id;
			query_string[query_string.length] = "item_id[]=" + $(this).attr('id').substr(4); 
			query_string[query_string.length] = "quantity[]=" + this.value;
			x++;
    });
	if (x > 0) {
		$.ajax({
			type: "POST",
			url: site_url + "ajax/update_whole_cart/" + Math.random(10000),
			data: query_string.join('&'),
			success: function(msg) {
				if (msg == "") {
					window.location = url;
				}
				else {
					alert(msg);
				}
			}
		});
	}else{
		window.location = url;
	}
}

function processSwapRequest(action, swapId) {
	if (!confirm('Are you sure you wish to ' + action + ' this swap request ?')) {
		return false;
	}
	
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/process_swap/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			response = httpObject.responseText.split('::');
			alert(response[1]);
			if (response[0] == '0') {
				document.location.reload();
			}
		}
	};
	var queryString = 'action=' + encodeURIComponent(action) + '&swap_id=' + encodeURIComponent(swapId);
	httpObject.send(queryString);
}

function popupSwapDetails(swapId) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/get_swap_popup_details/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', $(document).scrollTop() + 220);
			var linkPosition = $('#header-shopping-cart-link').offset();
			$('#shopping-cart-popup').css('left', linkPosition.left + $('#header-shopping-cart-link').width() - $('#shopping-cart-popup').width() + 4);
			$('#shopping-cart-popup').fadeIn('fast');
		}
	};
	httpObject.send('swap_id=' + encodeURIComponent(swapId));
}

function popupNotificationDetails(notifId) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/get_notification_mail/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			if (httpObject.responseText) {
				$('#shopping-cart-popup-content').html(httpObject.responseText);
				$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
				$('#lightbox_bg').show();
				$('#shopping-cart-popup').css('width', '932px');
				$('#shopping-cart-popup').css('left', '20%');
				$('#shopping-cart-popup-content').css('width', '896px');
				$('#shopping-cart-popup-content .title').css('width', '897px');
				$('#shopping-cart-popup-content .title').css('margin-bottom', '10px');
				$('#shopping-cart-popup #bottom-shadow').css('width', '926px');
				
				$('#shopping-cart-popup').fadeIn('fast', function() {
					$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
					$('#notif_container_' + notifId).removeClass('notification-unread');
				});
			}
		}
	};
	httpObject.send('notification_id=' + encodeURIComponent(notifId));
}

function popupReportItem(itemId) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/report_item_box/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			if (httpObject.responseText == '') {
				document.location.reload();
			}
			else if (httpObject.responseText == '-1') {
				alert('You have already reported this item to I-ELLA !');
			}
			else {
				$('#shopping-cart-popup-content').html(httpObject.responseText);
				$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
				$('#lightbox_bg').show();
				$('#shopping-cart-popup').css('top', ($(window).scrollTop() + $('#header').height()) + 'px').fadeIn('fast');
				$('#continue_link').bind('click', function() {
					var reason = $('#reason').val();
					if (reason == '') {
						alert('Please enter the reason for your report !');
						return false;
					}
					if (confirm('Are you sure you wish to report this item to I-ELLA ?')) {
						doReportItem(itemId, reason);
					}
				});
			}
		}
	}
	httpObject.send('item_id=' + encodeURIComponent(itemId));
}

function doReportItem(itemId, reason) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/report_item/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			alert(httpObject.responseText);
			hideCart();
		}
	}
	httpObject.send('item_id=' + encodeURIComponent(itemId) + '&reason=' + encodeURIComponent(reason));
}

function popupAddReview(itemId, sellerID, buyerID) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/add_review_box/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
			$('input.star').rating();
			$('#cancel-review').click(function() {
				hideCart();
				return false;
			});
			$('#delete-review').click(function() {
				if (confirm('Are you sure you wish to delete your review ?')) {
					submitDeleteReview(itemId, sellerID, buyerID);
				}
			});
			$('#submit-review').click(function() {
				if ($('#review_text').val() == '') {
					alert('Please enter your review!');
					return false;
				}
				var ratingValue;
				if (typeof($('#add-review-form input[type=radio]:checked').val()) == 'undefined') {
					ratingValue = 0;
				}
				else {
					ratingValue = $('#add-review-form input[type=radio]:checked').val();
				}
				
				submitAddReview(itemId, $('#review_text').val(), ratingValue, sellerID, buyerID);
			});
		}
	};
	httpObject.send('item_id=' + encodeURIComponent(itemId) + '&seller_id=' + encodeURIComponent(sellerID) + '&buyer_id=' + buyerID);
}

function submitAddReview(itemId, reviewText, ratingValue, sellerID, buyerID) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/submit_review/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			alert(httpObject.responseText);
			$('#lnk_review_' + itemId).html('<span class="lnk-star"></span>EDIT YOUR REVIEW');
			hideCart();
		}
	}
	httpObject.send('item_id=' + encodeURIComponent(itemId) + '&review_text=' + encodeURIComponent(reviewText) + '&rating_value=' + encodeURIComponent(ratingValue) + '&seller_id=' + encodeURIComponent(sellerID) + '&buyer_id=' + buyerID);
}

function submitDeleteReview(itemId, sellerID, buyerID) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/delete_review/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			alert(httpObject.responseText);
			$('#lnk_review_' + itemId).html('<span class="lnk-star"></span>WRITE A REVIEW');
			hideCart();
		}
	}
	httpObject.send('item_id=' + encodeURIComponent(itemId) + '&seller_id=' + encodeURIComponent(sellerID) + '&buyer_id=' + buyerID);
}

function populateSubcategories(category_id, subcategory_number, subcategory_active){
	$(document).ready(function() {
		if (category_id != "") {
			$.ajax({
				type: "POST",
				url: site_url + "ajax/populate_subcategories/" + Math.random(10000),
				data: "category_id=" + category_id + "&subcategory_number=" + subcategory_number + "&subcategory_active=" + subcategory_active,
				success: function(msg) {
					var myRez = msg.split("!!!");
					if (myRez[0] != 0) {
						if (subcategory_number == 1) {
							$('#subcategory1').html(myRez[0]);
							$('#subcategory1').show();
							$('#subcategory2').html('<select name="subcategory_swap2" class="select-upload-small"><option value="">SUBCATEGORY</option></select>');
							//$('#subcategory2').hide();
						}
						else 
							if (subcategory_number == 2) {
								$('#subcategory2').html(myRez[0]);
								$('#subcategory2').show();
								
							}
					}
					else {
						$('#subcategory2').html('<select name="subcategory_swap2" class="select-upload-small"><option value="">SUBCATEGORY</option></select>');
						//$('#subcategory2').hide();
					}
				}
			});
		}else{
			if (subcategory_number != 2) {
				$('#subcategory1').html('<select name="subcategory_swap1" class="select-upload-small"><option value="">SUBCATEGORY</option></select>');
				//$('#subcategory1').hide();
			}
			$('#subcategory2').html('<select name="subcategory_swap2" class="select-upload-small"><option value="">SUBCATEGORY</option></select>');
			//$('#subcategory2').hide();
		}
	});
}



function populateTrends(trend_id, trend_number, trend_active){
	$(document).ready(function() {
		if (trend_id != "") {
			$.ajax({
				type: "POST",
				url: site_url + "ajax/populate_trends/" + Math.random(10000),
				data: "trend_id=" + trend_id + "&trend_number=" + trend_number + "&trend_active=" + trend_active,
				success: function(msg) {
					setTimeout("", 1000);
					if (msg != 0) {
						if (trend_number == 1) {
							$('#trend1').html(msg);
							$('#trend1').show();
							$('#trend2').html('<select name="trend_swap2" class="select-upload-small"><option value="">SELECT</option></select>');
							//$('#trend2').hide();
						}
						else 
							if (trend_number == 2) {
								$('#trend2').html(msg);
								$('#trend2').show();
							}
					}
					else {
						$('#trend2').html('<select name="trend_swap2" class="select-upload-small"><option value="">SELECT</option></select>');
						//$('#trend2').hide();
					}
				}
			});
		}
		else{
			if(trend_number == 1) {
				$('#trend1').html('<select name="trend_swap1" class="select-upload-small"><option value="">SELECT</option></select>');
			}
			//$('#trend1').hide();
			$('#trend2').html('<select name="trend_swap2" class="select-upload-small"><option value="">SELECT</option></select>');
			//$('#trend2').hide();
		}
	});
}

function populateDesigners(designer_id, subcategory_number, subcategory_active){
	$(document).ready(function() {
		if (designer_id != "") {
			$("#designer_text").attr("readonly", true);
			$.ajax({
				type: "POST",
				url: site_url + "ajax/populate_designers/" + Math.random(10000),
				data: "designer_id=" + designer_id + "&subcategory_number=" + subcategory_number + "&subcategory_active=" + subcategory_active,
				success: function(msg) {
					var myRez = msg.split("!!!");
					if (myRez[0] != 0) {						
						if (subcategory_number == 1) {
							$('#designer1').html(myRez[0]);
							$('#designer1').show();
							//$('#span-designer').hide();
							$('#designer2').html('<select name="designer_swap2" class="select-upload-small"><option value="">SELECT</option></select>');							
							//$('#designer2').hide();
							
						}
						else 
							if (subcategory_number == 2) {
								$('#designer2').html(myRez[0]);
								$('#designer').show();								
							}
					}
					else {						
						$('#designer2').html('<select name="designer_swap2" class="select-upload-small"><option value="">SELECT</option></select>');
						//$('#designer2').hide();						
					}
				}
			});
		}
		else{
			if(subcategory_number == 1) {
				$('#designer_text').removeAttr("readonly"); 
			}
			if (subcategory_number != 2) {
				$('#designer1').html('<select name="designer_swap1" class="select-upload-small"><option value="">SELECT</option></select>');
				//$('#designer1').hide();
				$('#span-designer').show();
			}
			$('#designer2').html('<select name="designer_swap2" class="select-upload-small"><option value="">SELECT</option></select>');
			//$('#designer2').hide();
		}
	});
}

function populateSwapSubcategories(category_id, subcategory_active){
	$(document).ready(function() {
		if (category_id != "") {
			$.ajax({
				type: "POST",
				url: site_url + "ajax/populate_swap_subcategories/" + Math.random(10000),
				data: "category_id=" + category_id + "&subcategory_active=" + subcategory_active,
				success: function(msg) {
					$('select[name=swap_subcategory]').html(msg);
				}
			});
		}
	});
}

function delete_db_looking(row){
	$('#looking_for_' + row).hide('fast');
	$('#looking_for_' + row).html('');
}

function addToItemSwap(){
	
	var swap_text = $('input[name=looking_for_text]').val();
	var increment = $('input[name=increment_swap]').val();

	var swap_designer = $('select[name=swap_designer]').val();
	swap_designer = jQuery.trim(swap_designer);
	
	var swap_category = $('select[name=swap_category]').val();
	swap_category = jQuery.trim(swap_category);
	
	var swap_subcategory = $('select[name=swap_subcategory]').val();
	swap_subcategory = jQuery.trim(swap_subcategory);
	
	var swap_action = "";
	
	
	if (swap_designer != "") {
		swap_action += swap_designer;
	}
	if (swap_category != "") {
		if(swap_designer != ""){
			swap_action +=  '//' + swap_category;
		}else{
			swap_action +=  swap_category;
		}
		
	}
	if (swap_subcategory != "") {
		swap_action += '//' + swap_subcategory;
	}
	
	if(swap_text != "" && swap_action == ""){
		swap_action += swap_text;
	}else if(swap_text != ""){
		swap_action += '//' + swap_text;
	}
	if (swap_action != "") {
		
		swap_action = jQuery.trim(swap_action)
		$('.wishlist-right ul').append('<input type="hidden" name="swap_'+ increment +'" value="' + swap_action.toUpperCase() + '" /><li id="looking_for_' + increment + '"><a style="float: right;" href="javascript: void(0);" title="DELETE LOOKING FOR" onclick="delete_db_looking('+  increment +');">X</a>' + swap_action.toUpperCase() + '</li>');
		increment++;
		$('input[name=increment_swap]').val(increment);
		$("select[name='swap_designer']").find('option:first').attr('selected', 'selected').parent('select');
		$("select[name='swap_category']").find('option:first').attr('selected', 'selected').parent('select');
		$("select[name='swap_subcategory']").find('option:first').attr('selected', 'selected').parent('select');
		$("input[name='looking_for_text']").val('');
	}

}

function cnt(w){
	var y=w.value;
	var r = 0;
	a=y.replace(/\s/g,' ');
	a=a.split(' ');
	for (z=0; z<a.length; z++) {
		if (a[z].length > 0) r++;
	}
	
	if(r == 50){
		alert('You have 50 words in your story!')
		
	}
}

function sendFriendRequest(userId, action) {
	httpObject = getXMLHTTPObject();
	httpObject.open('POST', site_url + '/ajax/send_friend_request/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			eval('response = ' + httpObject.responseText);
			alert(response.message);
			if (response.status == 0) { // successful "add friend" request
				$('<span />').html(response.link_value).insertAfter('#friend_req_link');
				$('#friend_req_link').hide();
				$('<span />').html(response.link_value).insertAfter('#friend_req_link1');
				$('#friend_req_link1').hide();
			}
			if (response.status == 2) { // successful "reactivate friend" request
				$('#friend_req_link').html(response.link_value);
				$('#friend_req_link').click(function() {
					sendFriendRequest(userId, "delete");
				});
				
				$('#friend_req_link1').html(response.link_value);
				$('#friend_req_link1').click(function() {
					sendFriendRequest(userId, "delete");
				});
			}
			else if (response.status == 1) { // successful "remove me as a friend" request
				$('#friend_req_link').html(response.link_value);
				$('#friend_req_link').click(function() {
					sendFriendRequest(userId, "reactivate");
				});
			}
			else if (response.status == 3) { // successful "accept"/"reject" request
				document.location.reload();
			}
		}
	};
	httpObject.send('user_id=' + encodeURIComponent(userId) + '&action=' + encodeURIComponent(action));
}

function submitTransactionTimeFilter() {
	var startMonth = $('#start_month').val();
	var endMonth = $('#end_month').val();
	var startYear = $('#start_year').val();
	var endYear = $('#end_year').val();
	
	if (startMonth < 10) {
		startMonth = '0' + startMonth;
	}
	if (endMonth < 10) {
		endMonth = '0' + endMonth;
	}
	
	with (document.time_filter) {
		position.value = $('#position').val();
		start.value = startYear + '-' + startMonth;
		end.value = endYear + '-' + endMonth;
		submit();
	}
}

/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�rn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *          
 *   class: Inside the class attribute, wrapped in curly braces: { }
 *   
 *   elem:  Inside a child element (e.g. a script tag). The
 *          name parameter indicates *which* element.
 *          
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
	metadata : {
		defaults : {
			type: 'class',
			name: 'metadata',
			cre: /({.*})/,
			single: 'metadata'
		},
		setType: function( type, name ){
			this.defaults.type = type;
			this.defaults.name = name;
		},
		get: function( elem, opts ){
			var settings = $.extend({},this.defaults,opts);
			// check for empty string in single property
			if ( !settings.single.length ) settings.single = 'metadata';
			
			var data = $.data(elem, settings.single);
			// returned cached data if it already exists
			if ( data ) return data;
			
			data = "{}";
			
			if ( settings.type == "class" ) {
				var m = settings.cre.exec( elem.className );
				if ( m )
					data = m[1];
			} else if ( settings.type == "elem" ) {
				if( !elem.getElementsByTagName ) return;
				var e = elem.getElementsByTagName(settings.name);
				if ( e.length )
					data = $.trim(e[0].innerHTML);
			} else if ( elem.getAttribute != undefined ) {
				var attr = elem.getAttribute( settings.name );
				if ( attr )
					data = attr;
			}
			
			if ( data.indexOf( '{' ) <0 )
			data = "{" + data + "}";
			
			data = eval("(" + data + ")");
			
			$.data( elem, settings.single, data );
			return data;
		}
	}
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
	return $.metadata.get( this[0], opts );
};

})(jQuery);

/*
 ### jQuery Star Rating Plugin v3.13 - 2009-03-26 ###
 * Home: http://www.fyneworks.com/jquery/star-rating/
 * Code: http://code.google.com/p/jquery-star-rating-plugin/
 *
	* Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 ###
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/
	
	// IE6 Background Image Fix
	if ($.browser.msie) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { };
	// Thanks to http://www.visualjquery.com/rating/rating_redux.html
	
	// plugin initialization
	$.fn.rating = function(options){
		if(this.length==0) return this; // quick fail
		
		// Handle API methods
		if(typeof arguments[0]=='string'){
			// Perform API methods on individual elements
			if(this.length>1){
				var args = arguments;
				return this.each(function(){
					$.fn.rating.apply($(this), args);
    });
			};
			// Invoke API method handler
			$.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
			// Quick exit...
			return this;
		};
		
		// Initialize options for this call
		var options = $.extend(
			{}/* new object */,
			$.fn.rating.options/* default options */,
			options || {} /* just-in-time options */
		);
		
		// Allow multiple controls with the same name by making each call unique
		$.fn.rating.calls++;
		
		// loop through each matched element
		this
		 .not('.star-rating-applied')
			.addClass('star-rating-applied')
		.each(function(){
			
			// Load control parameters / find context / etc
			var control, input = $(this);
			var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,'');
			var context = $(this.form || document.body);
			
			// FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23
			var raters = context.data('rating');
			if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls };
			var rater = raters[eid];
			
			// if rater is available, verify that the control still exists
			if(rater) control = rater.data('rating');
			
			if(rater && control)//{// save a byte!
				// add star to control if rater is available and the same control still exists
				control.count++;
				
			//}// save a byte!
			else{
				// create new control if first star or control element was removed/replaced
				
				// Initialize options for this raters
				control = $.extend(
					{}/* new object */,
					options || {} /* current call options */,
					($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */
					{ count:0, stars: [], inputs: [] }
				);
				
				// increment number of rating controls
				control.serial = raters.count++;
				
				// create rating element
				rater = $('<span class="star-rating-control"/>');
				input.before(rater);
				
				// Mark element for initialization (once all stars are ready)
				rater.addClass('rating-to-be-drawn');
				
				// Accept readOnly setting from 'disabled' property
				if(input.attr('disabled')) control.readOnly = true;
				
				// Create 'cancel' button
				rater.append(
					control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>')
					.mouseover(function(){
						$(this).rating('drain');
						$(this).addClass('star-rating-hover');
						//$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).removeClass('star-rating-hover');
						//$(this).rating('blur');
					})
					.click(function(){
					 $(this).rating('select');
					})
					.data('rating', control)
				);
				
			}; // first element of group
			
			// insert rating star
			var star = $('<div class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
			rater.append(star);
			
			// inherit attributes from input element
			if(this.id) star.attr('id', this.id);
			if(this.className) star.addClass(this.className);
			
			// Half-stars?
			if(control.half) control.split = 2;
			
			// Prepare division control
			if(typeof control.split=='number' && control.split>0){
				var stw = ($.fn.width ? star.width() : 0) || control.starWidth;
				var spi = (control.count % control.split), spw = Math.floor(stw/control.split);
				star
				// restrict star's width and hide overflow (already in CSS)
				.width(spw)
				// move the star left by using a negative margin
				// this is work-around to IE's stupid box model (position:relative doesn't work)
				.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
			};
			
			// readOnly?
			if(control.readOnly)//{ //save a byte!
				// Mark star as readOnly so user can customize display
				star.addClass('star-rating-readonly');
			//}  //save a byte!
			else//{ //save a byte!
			 // Enable hover css effects
				star.addClass('star-rating-live')
				 // Attach mouse events
					.mouseover(function(){
						$(this).rating('fill');
						$(this).rating('focus');
					})
					.mouseout(function(){
						$(this).rating('draw');
						$(this).rating('blur');
					})
					.click(function(){
						$(this).rating('select');
					})
				;
			//}; //save a byte!
			
			// set current selection
			if(this.checked)	control.current = star;
			
			// hide input element
			input.hide();
			
			// backward compatibility, form element to plugin
			input.change(function(){
    $(this).rating('select');
   });
			
			// attach reference to star to input element and vice-versa
			star.data('rating.input', input.data('rating.star', star));
			
			// store control information in form (or body when form not available)
			control.stars[control.stars.length] = star[0];
			control.inputs[control.inputs.length] = input[0];
			control.rater = raters[eid] = rater;
			control.context = context;
			
			input.data('rating', control);
			rater.data('rating', control);
			star.data('rating', control);
			context.data('rating', raters);
  }); // each element
		
		// Initialize ratings (first draw)
		$('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn');
		
		return this; // don't break the chain...
	};
	
	/*--------------------------------------------------------*/
	
	/*
		### Core functionality and API ###
	*/
	$.extend($.fn.rating, {
		// Used to append a unique serial number to internal control ID
		// each time the plugin is invoked so same name controls can co-exist
		calls: 0,
		
		focus: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.focus) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // focus handler, as requested by focusdigital.co.uk
			if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.focus
		
		blur: function(){
			var control = this.data('rating'); if(!control) return this;
			if(!control.blur) return this; // quick fail if not required
			// find data for event
			var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null );
   // blur handler, as requested by focusdigital.co.uk
			if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]);
		}, // $.fn.rating.blur
		
		fill: function(){ // fill to the current mouse position.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars and highlight them up to this element
			this.rating('drain');
			this.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-hover');
		},// $.fn.rating.fill
		
		drain: function() { // drain all the stars.
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// Reset all stars
			control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover');
		},// $.fn.rating.drain
		
		draw: function(){ // set value and stars to reflect current selection
			var control = this.data('rating'); if(!control) return this;
			// Clear all stars
			this.rating('drain');
			// Set control value
			if(control.current){
				control.current.data('rating.input').attr('checked','checked');
				control.current.prevAll().andSelf().filter('.rater-'+ control.serial).addClass('star-rating-on');
			}
			else
			 $(control.inputs).removeAttr('checked');
			// Show/hide 'cancel' button
			control.cancel[control.readOnly || control.required?'hide':'show']();
			// Add/remove read-only classes to remove hand pointer
			this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly');
		},// $.fn.rating.draw
		
		
		
		
		
		select: function(value,wantCallBack){ // select a value
					
					// ***** MODIFICATION *****
					// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
					//
					// ***** LIST OF MODIFICATION *****
					// ***** added Parameter wantCallBack : false if you don't want a callback. true or undefined if you want postback to be performed at the end of this method'
					// ***** recursive calls to this method were like : ... .rating('select') it's now like .rating('select',undefined,wantCallBack); (parameters are set.)
					// ***** line which is calling callback
					// ***** /LIST OF MODIFICATION *****
			
			var control = this.data('rating'); if(!control) return this;
			// do not execute when control is in read-only mode
			if(control.readOnly) return;
			// clear selection
			control.current = null;
			// programmatically (based on user input)
			if(typeof value!='undefined'){
			 // select by index (0 based)
				if(typeof value=='number')
 			 return $(control.stars[value]).rating('select',undefined,wantCallBack);
				// select by literal value (must be passed as a string
				if(typeof value=='string')
					//return
					$.each(control.stars, function(){
						if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack);
					});
			}
			else
				control.current = this[0].tagName=='INPUT' ?
				 this.data('rating.star') :
					(this.is('.rater-'+ control.serial) ? this : null);

			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
			// find data for event
			var input = $( control.current ? control.current.data('rating.input') : null );
			// click callback, as requested here: http://plugins.jquery.com/node/1655
					
					// **** MODIFICATION *****
					// Thanks to faivre.thomas - http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=27
					//
					//old line doing the callback :
					//if(control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
					//
					//new line doing the callback (if i want :)
					if((wantCallBack ||wantCallBack == undefined) && control.callback) control.callback.apply(input[0], [input.val(), $('a', control.current)[0]]);// callback event
					//to ensure retro-compatibility, wantCallBack must be considered as true by default
					// **** /MODIFICATION *****
					
  },// $.fn.rating.select
		
		
		
		
		
		readOnly: function(toggle, disable){ // make the control read-only (still submits value)
			var control = this.data('rating'); if(!control) return this;
			// setread-only status
			control.readOnly = toggle || toggle==undefined ? true : false;
			// enable/disable control value submission
			if(disable) $(control.inputs).attr("disabled", "disabled");
			else     			$(control.inputs).removeAttr("disabled");
			// Update rating control state
			this.data('rating', control);
			// Update display
			this.rating('draw');
		},// $.fn.rating.readOnly
		
		disable: function(){ // make read-only and never submit value
			this.rating('readOnly', true, true);
		},// $.fn.rating.disable
		
		enable: function(){ // make read/write and submit value
			this.rating('readOnly', false, false);
		}// $.fn.rating.select
		
 });
	
	/*--------------------------------------------------------*/
	
	/*
		### Default Settings ###
		eg.: You can override default control like this:
		$.fn.rating.options.cancel = 'Clear';
	*/
	$.fn.rating.options = { //$.extend($.fn.rating, { options: {
			cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
			cancelValue: '',           // value to submit when user click the 'cancel' link
			split: 0,                  // split the star into how many parts?
			
			// Width of star image in case the plugin can't work it out. This can happen if
			// the jQuery.dimensions plugin is not available OR the image is hidden at installation
			starWidth: 16//,
			
			//NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code!
			//half:     false,         // just a shortcut to control.split = 2
			//required: false,         // disables the 'cancel' button so user can only select one of the specified values
			//readOnly: false,         // disable rating plugin interaction/ values cannot be changed
			//focus:    function(){},  // executed when stars are focused
			//blur:     function(){},  // executed when stars are focused
			//callback: function(){},  // executed when a star is clicked
 	}; //} });
	
/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/


/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only things you may need to change in this file are the following
variables: checkboxHeight, radioHeight and selectWidth (lines 24, 25, 26)

The numbers you set for checkboxHeight and radioHeight should be one quarter
of the total height of the image want to use for checkboxes and radio
buttons. Both images should contain the four stages of both inputs stacked
on top of each other in this order: unchecked, unchecked-clicked, checked,
checked-clicked.

You may need to adjust your images a bit if there is a slight vertical
movement during the different stages of the button activation.

The value of selectWidth should be the width of your select list image.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');
	
/* No need to change anything after this */

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className.indexOf("styled") !== -1 && inputs[a].className.indexOf("custom-style-applied") == -1) {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;
				inputs[a].className += " custom-style-applied";
				
				if(inputs[a].className.indexOf("white") !== -1){
					span[a].className += " radio-white";
				}

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				if(!inputs[a].getAttribute("disabled")) {
					span[a].onmousedown = Custom.pushed;
					span[a].onmouseup = Custom.check;
				} else {
					span[a].className = span[a].className += " disabled";
				}
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className.indexOf("styled") !== -1) {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				if(!inputs[a].getAttribute("disabled")) {
					inputs[a].onchange = Custom.choose;
				} else {
					inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
				}
			}
		}
		document.onmouseup = Custom.clear;
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className.indexOf("styled") !== -1) {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className.indexOf("styled") !== -1) {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className.indexOf("styled") !== -1) {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className.indexOf("styled") !== -1) {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}

$(document).ready(function() {
	Custom.init();
  	$('.item-details').ImageOverlay({
	  overlay_speed: 'fast',
	  overlay_speed_out: 'slow'
	});
	$('.item_details_featured').ImageOverlay({
		width : 102,
		height : 96,
		overlay_speed: 'fast',
		overlay_speed_out: 'slow'
	});
	
	if (navigator.platform.indexOf('Mac') != -1) {   // all Mac browsers
		$('.home_cause').css('height', '97px');
	}
	
	if (navigator.platform.indexOf('Mac') != -1 && navigator.userAgent.indexOf('Safari') != -1) {   //Safari for Mac only
		$('ul.dropdown-categories ul').css('margin', '0').css('top', '21px');
		$('ul.dropdown-designers ul').css('margin', '0').css('top', '21px');
		$('ul.dropdown-categories ul ul').css('top', '20px');
		$('ul.dropdown-designers ul ul').css('top', '20px');
		$('#feature_blogger_caption').css('height', '17px');
		$('#search-query').css('padding-top','1px');
		$('#search-submit').css('margin-top','2px');
		if ($('#right').length > 0) {
			if ($('#right').css('top') == '260px') {
				$('#right').css('top', '250px');
			}
		}
	}
	if (navigator.userAgent.indexOf('Version/3') != -1 && navigator.userAgent.indexOf('Safari') != -1) { // Safari 3.x only
		$('ul.dropdown-categories ul').css('margin', '0').css('top', '21px');
		$('ul.dropdown-designers ul').css('margin', '0').css('top', '21px');
		$('ul.dropdown-categories ul ul').css('top', '20px');
		$('ul.dropdown-designers ul ul').css('top', '20px');
	}
	
	if (navigator.userAgent.indexOf('Firefox/1.5') != -1 || navigator.userAgent.indexOf('Firefox/2') != -1) { // Firefox 1.5.x and 2.x
		$('#search-query').css('padding-top', '4px');
		$('.right_refine_search a span').css('display', 'block').css('float', 'left').css('margin', '4px 5px 0px 0px');
		$('.sort a.sort-buy, .sort a.sort-borrow, .sort a.sort-swap').css('display', 'block').css('float', 'left');
		$('.sort a span').css('display', 'block').css('float', 'left').css('margin', '3px 5px 0px 0px');
	}
});

function check_featured(item_id){
	if (item_id != "") {
		if ($('input[name=featured_item_'+ item_id +']').is(':checked')) {
		   var featured_value = 1;
		}else{
			var featured_value = 0;
		}
		$.ajax({
			type: "POST",
			url: site_url + "ajax/set_featured_item/" + Math.random(10000),
			data: "active=" + featured_value + "&item_id=" + item_id,
			success: function(msg) {
				if(msg > 4){
					alert('You have ' + msg + ' featured items selected');
				}
			}
		});

	}
}

function check_love(item_id){
	if (item_id != "") {
		if ($('input[name=iella_love_'+ item_id +']').is(':checked')) {
		   var love_value = 1;
		}else{
			var love_value = 0;
		}
		
		$.ajax({
			type: "POST",
			url: site_url + "ajax/set_iella_love_item/" + Math.random(10000),
			data: "active=" + love_value + "&item_id=" + item_id,
			success: function(msg) {
				if(msg > 8){
					alert('You have ' + msg + ' items for I-ELLA loves');
				}
			}
		});

	}
}

function popupSizesInfo() {
	httpObject = getXMLHTTPObject();
	httpObject.open('GET', site_url + '/ajax/size_info_popup/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', '158px').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				return submitCauseSuggestion();
			});
			Custom.init();
		}
	};
	httpObject.send(null);
}

function get_size_options(size_type, size_select) {
	if(size_type > 0 && size_type != 4) {		
		params = 'size_type_id=' + encodeURIComponent(size_type) + '&size_select_id=' + encodeURIComponent(size_select);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + '/ajax/get_size_options/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				$("#size_select_box").show();
				if(size_type == 1) {
					$("#size_select_box_info").show();
				}
				else {
					$("#size_select_box_info").hide();
				}
				$("#size_select_box").html(httpObject.responseText);
			}
		};
		httpObject.send(params);
	}
	else {
		$("#size_select_box").hide();
		$("#size_select_box").html('');
		$("#size_select_box_info").hide();
	}
}

function check_google_pending_orders(order_type,item_id) {
	if(order_type != '') {
		params = 'order_type=' + encodeURIComponent(order_type) + '&item_id=' + encodeURIComponent(item_id);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/check_google_pending_order/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == '0') {
					window.location.reload();
				}				
				else {
					setTimeout(function(){check_google_pending_orders(order_type,item_id)},10000);
				}
			}
		};
		httpObject.send(params);		
	}
}

	
	function textCounter(field,cntfield,maxlimit) {	
		if (field.value.length > maxlimit) // if too long...trim it!
			field.value = field.value.substring(0, maxlimit);
			// otherwise, update 'characters left' counter
		else
			cntfield.value = maxlimit - field.value.length;
	}
	
	function create_new_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type) {
		img_nr++;
		myCounterImg = img_nr;
		idW = myCounterImg;				
		//alert(img_nr+'-'+img_id);
		if(img_id == 0 ) {    // if we don't have an image id 
			img_id = img_nr;
		}
		
		try {
			element = document.createElement("span");
			element.id = "holderImg_"+myCounterImg;			
		}
		catch (e) {
			element = document.createElement("span");
			element.setAttribute("id", "holderImg_"+myCounterImg);
		}
		
		if(add_more_img_box) {
			txt = '';
			txt+= '<div class="picture" id="pictureDiv'+idW+'" style="text-align: center;" >';
					txt+= '<img id="'+image_box_id+'_'+idW+'" src="'+site_url+'img/'+default_img+'" alt="image" style="cursor: default" />';
					txt+= '<span id="lnk_'+idW+'"><a class="upload" id="'+image_box_id+idW+'" style="cursor:pointer;cursor:hand" >BROWSE</a></span>';
					//txt+= '<input type="hidden" id="img_hid_watch'+idW+'" name="src_img['+(idW-1)+']" value="" /> ';
			txt+= '</div>';
			if(ajax_function == 'upload_blogger_picture_edit') {
				document.getElementById("feature_seller_more").appendChild(element);
			}
			else {
				document.getElementById("holderImg_"+img_id).appendChild(element);
			}
					
			mySpan = document.getElementById("holderImg_"+myCounterImg);		
			mySpan.innerHTML = txt;
		}
		
		var button = $('#img'+idW), interval;
		var id = img_nr;	
		new AjaxUpload(button, {
			action: site_url + 'ajax/' + ajax_function + '/' + Math.random(10000), 
			
			data: {
				extraType : img_nr
			  },
			
			onSubmit : function(file, ext){
			   if (! (ext && /^jpg$/.test(ext))) {
					// extension is not allowed
					alert('Error: invalid file extension');
					// cancel upload
					return false;
				}

				button.text('BROWSE');
				this.disable();	
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13){
						button.text(text);
					} else {
						button.text('Uploading');
					}
				}, 200);
			},
			onComplete: function(file, response) {
				if(ajax_function == 'upload_blogger_picture_edit') {
					more_seller_img++;
					if(more_seller_img < 2 ) {
						more_seller_img = 2;
					} 
				}
				
				window.clearInterval(interval);	
				this.enable();
				if(response == 'error_size') {
					button.text('BROWSE');
					msg = document.getElementById('upload_file_size_exceeded').value;
					alert(msg);							
				}
				else if(response == 'error_ext') {
					button.text('BROWSE');
					msg = document.getElementById('upload_unsupported_extension').value;
					alert(msg);							
				}
				else {
					var myRez = response.split("!!!");
					var rez = myRez[0]+'?'+(new Date()).getTime();
					document.getElementById('img_'+id).src = rez;
					add_delete = '<a href="#" id="img'+id+'" class="upload" onclick ="delete_my_generic_image_box('+ uid+',\''+img_type+'\','+id+',\'pictureDiv'+id+'\'); return false;"> DELETE</a>';
					$("#lnk_"+id).html(add_delete);
					if(add_more_img_box) {
						create_new_upload_image_box(image_box_id,default_img,idW,add_more_img_box,ajax_function,uid,img_type);
					}
				}
			}
		});
	}	
	
	
	function delete_my_generic_image_box(uid,img_type,img_id,div_id) {				
		if(img_type == 'blogger') {
			more_seller_img-- ;		
			if(more_seller_img < 1) {
				alert('You must have at least 1 picture');
			}
		}
		else {
			more_seller_img = 2;
		}
		
		if(img_type != '' && more_seller_img > 0) {
			params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent(img_id)+ '&uid='+encodeURIComponent(uid);
			httpObject = getXMLHTTPObject();
			httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if(httpObject.responseText == 'success') {
						$("#"+div_id).remove();
					}
					else {
						alert('There was an error! Please refresh the page and try again.');
					}
				}
			};
			httpObject.send(params);		
		}
		
	}
	
	function delete_celebrity_image_box(uid,img_type,img_id,div_id,folder_id) {
		if(img_id == celeb_last_img) {
			celeb_last_img -- ;
			//img_nr = last_img--;
		}		
		if(img_type != '') {
			params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent(img_id)+ '&uid='+encodeURIComponent(uid)+'&folder_id='+encodeURIComponent(folder_id);
			httpObject = getXMLHTTPObject();
			httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if(httpObject.responseText == 'success') {
						$("#"+div_id).remove();
					}
					else {
						alert('There was an error! Please refresh the page and try again.');
					}
				}
			};
			httpObject.send(params);		
		}
		
	}
	
	
	function delete_blogger_home_image(uid,img_id,new_img) {
		params = 'img_type='+encodeURIComponent('blogger_home_img')+'&img_id='+encodeURIComponent('1')+ '&uid='+encodeURIComponent(uid);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					document.getElementById(img_id).src = site_url+'img/'+new_img+'.jpg?'+(new Date()).getTime();;
				}
				else {
					alert('There was an error! Please refresh the page and try again.');
				}
			}
		};
		httpObject.send(params);
	}
	
	function delete_blogger_charity_image(uid,img_id,new_img) {
		params = 'img_type='+encodeURIComponent('blogger_charity_img')+'&img_id='+encodeURIComponent('1')+ '&uid='+encodeURIComponent(uid);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					document.getElementById('imgCharity').src = site_url+'img/'+new_img+'.jpg?'+(new Date()).getTime();;
				}
				else {
					alert('There was an error! Please refresh the page and try again.');
				}
			}
		};
		httpObject.send(params);
	}
	
	function check_choose(charity_id){
		if (charity_id != "") {
			$.ajax({
				type: "POST",
				url: site_url + "ajax/set_iella_choose/" + Math.random(10000),
				data: "charity_id=" + charity_id,
				success: function(msg) {
					window.location.reload();
				}
			});

		}
	}
	
	
	function delete_simple_image(uid,img_id,new_img,img_type,folder_id) {
		params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent('1')+ '&uid='+encodeURIComponent(uid)+'&folder_id='+encodeURIComponent(folder_id);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					document.getElementById(img_id).src = site_url+'img/'+new_img+'.jpg?'+(new Date()).getTime();;
				}
				else {
					alert('There was an error! Please refresh the page and try again.');
				}
			}
		};
		httpObject.send(params);
	}
	
	function create_new_celebrity_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id) {
		celeb_img_nr;
		celeb_img_nr++;
		myCounterImg = celeb_img_nr;
		idW = myCounterImg;				
		
		if(img_id == 0 ) {    // if we don't have an image id 
			img_id = celeb_img_nr;
		}
		
		try {
			element = document.createElement("span");
			element.id = "celeb_holderImg_"+myCounterImg;			
		}
		catch (e) {
			element = document.createElement("span");
			element.setAttribute("id", "celeb_holderImg_"+myCounterImg);
		}
		
		if(add_more_img_box) {
			txt = '';
			txt+= '<div class="picture" id="pictureDiv'+idW+'" style="text-align: center;" >';
					txt+= '<img id="'+image_box_id+'_'+idW+'" src="'+site_url+'img/'+default_img+'" alt="image" style="cursor: default" />';
					txt+= '<span id="celeb_lnk_'+idW+'"><a class="upload" id="'+image_box_id+idW+'" style="cursor:pointer;cursor:hand" >BROWSE</a></span>';
					//txt+= '<input type="hidden" id="img_hid_watch'+idW+'" name="src_img['+(idW-1)+']" value="" /> ';
			txt+= '</div>';
			
			document.getElementById("celeb_holderImg_"+img_id).appendChild(element);
					
			mySpan = document.getElementById("celeb_holderImg_"+myCounterImg);		
			mySpan.innerHTML = txt;
		}
		
		var button = $('#celeb_img'+idW), interval;
		var id = celeb_img_nr;	
		new AjaxUpload(button, {
			action: site_url + 'ajax/' + ajax_function + '/' + Math.random(10000), 
			
			data: {
				extraType: id,
				celebrity_id: folder_id 
			  },
			
			onSubmit : function(file, ext){
			   if (! (ext && /^jpg$/.test(ext))) {
					// extension is not allowed
					alert('Error: invalid file extension');
					// cancel upload
					return false;
				}

				button.text('BROWSE');
				this.disable();	
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13){
						button.text(text);
					} else {
						button.text('Uploading');
					}
				}, 200);
			},
			onComplete: function(file, response) {
				window.clearInterval(interval);	
				this.enable();
				if(response == 'error_size') {
					button.text('BROWSE');
					msg = document.getElementById('upload_file_size_exceeded').value;
					alert(msg);							
				}
				else if(response == 'error_ext') {
					button.text('BROWSE');
					msg = document.getElementById('upload_unsupported_extension').value;
					alert(msg);							
				}
				else {
					var myRez = response.split("!!!");
					var rez = myRez[0]+'?'+(new Date()).getTime(); 
					document.getElementById('celeb_img_'+id).src = rez;
					add_delete = '<a href="#" id="celeb_img'+idW+'" class="upload" onclick ="delete_celebrity_image_box('+ uid+',\''+img_type+'\','+id+',\'pictureDiv'+idW+'\','+folder_id+'); return false;"> DELETE</a>';
					$("#celeb_lnk_"+id).html(add_delete);
					if(add_more_img_box) {
						create_new_celebrity_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id);
					}
				}
			}
		});
	}

	function create_new_charity_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id) {
		mcharity_img_nr;
		mcharity_img_nr++;
		myCounterCharityImg = mcharity_img_nr;
		idW = myCounterCharityImg;				
		
		if(img_id == 0 ) {    // if we don't have an image id 
			img_id = mcharity_img_nr;
		}
		
		try {
			element = document.createElement("span");
			element.id = "mcharity_holderImg_"+myCounterCharityImg;			
		}
		catch (e) {
			element = document.createElement("span");
			element.setAttribute("id", "mcharity_holderImg_"+myCounterCharityImg);
		}
		
		if(add_more_img_box) {
			txt = '';
			txt+= '<div class="picture" id="mcharity_pictureDiv'+idW+'" style="text-align: center;" >';
					txt+= '<img id="'+image_box_id+'_'+idW+'" src="'+site_url+'img/'+default_img+'" alt="image" style="cursor: default" />';
					txt+= '<span id="mcharity_lnk_'+idW+'"><a class="upload" id="'+image_box_id+idW+'" style="cursor:pointer;cursor:hand" >BROWSE</a></span>';
					//txt+= '<input type="hidden" id="img_hid_watch'+idW+'" name="src_img['+(idW-1)+']" value="" /> ';
			txt+= '</div>';
			
			document.getElementById("mcharity_holderImg_"+img_id).appendChild(element);
					
			mySpan = document.getElementById("mcharity_holderImg_"+myCounterCharityImg);		
			mySpan.innerHTML = txt;
		}
		
		var button = $('#img_more_charity'+idW), interval;
		var id = mcharity_img_nr;	
		new AjaxUpload(button, {
			action: site_url + 'ajax/' + ajax_function + '/' + Math.random(10000), 
			
			data: {
				extraType: id,
				celebrity_id: folder_id 
			  },
			
			onSubmit : function(file, ext){
			   if (! (ext && /^jpg$/.test(ext))) {
					// extension is not allowed
					alert('Error: invalid file extension');
					// cancel upload
					return false;
				}

				button.text('BROWSE');
				this.disable();	
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13){
						button.text(text);
					} else {
						button.text('Uploading');
					}
				}, 200);
			},
			onComplete: function(file, response) {
				window.clearInterval(interval);	
				this.enable();
				if(response == 'error_size') {
					button.text('BROWSE');
					msg = document.getElementById('upload_file_size_exceeded').value;
					alert(msg);							
				}
				else if(response == 'error_ext') {
					button.text('BROWSE');
					msg = document.getElementById('upload_unsupported_extension').value;
					alert(msg);							
				}
				else {
					var myRez = response.split("!!!");
					var rez = myRez[0]+'?'+(new Date()).getTime(); 
					document.getElementById('img_more_charity_'+id).src = rez;
					add_delete = '<a href="#" id="img_more_charity'+idW+'" class="upload" onclick ="delete_more_charity_image_box('+ uid+',\''+img_type+'\','+id+',\'mcharity_pictureDiv'+idW+'\','+folder_id+'); return false;"> DELETE</a>';
					$("#mcharity_lnk_"+id).html(add_delete);
					if(add_more_img_box) {
						create_new_charity_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id);
					}
				}
			}
		});
	}
	
	function delete_more_charity_image_box(uid,img_type,img_id,div_id,folder_id) {
		if(img_type == 'blogger_more_charity_images') {
			more_blogger_charity_img-- ;		
			if(more_blogger_charity_img < 1) {
				alert('You must have at least 1 picture');
			}
		}
		else {
			more_blogger_charity_img = 2;
		}
		
		if(img_type != '' && more_blogger_charity_img > 0) {
			params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent(img_id)+ '&uid='+encodeURIComponent(uid)+'&folder_id='+encodeURIComponent(folder_id);
			httpObject = getXMLHTTPObject();
			httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if(httpObject.responseText == 'success') {
						$("#"+div_id).remove();
					}
					else {
						alert('There was an error! Please refresh the page and try again.');
					}
				}
			};
			httpObject.send(params);		
		}
		
	}
	
	function delete_prelunch_images(uid,img_type,img_id,div_id,folder_id) {
		if(img_id == mcharity_last_img) {
			mcharity_last_img -- ;
			//img_nr = last_img--;
		}		
		if(img_type != '') {
			params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent(img_id)+ '&uid='+encodeURIComponent(uid)+'&folder_id='+encodeURIComponent(folder_id);
			httpObject = getXMLHTTPObject();
			httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if(httpObject.responseText == 'success') {
						$("#"+div_id).remove();
					}
					else {
						alert('There was an error! Please refresh the page and try again.');
					}
				}
			};
			httpObject.send(params);		
		}
		
	}
	
	
	function edit_interview_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id) {
		img_nr++;
		myCounterImg = img_nr;
		idW = myCounterImg;				
		
		if(img_id == 0 ) {    // if we don't have an image id 
			img_id = img_nr;
		}
		
		try {
			element = document.createElement("span");
			element.id = "holderImg_"+myCounterImg;			
		}
		catch (e) {
			element = document.createElement("span");
			element.setAttribute("id", "holderImg_"+myCounterImg);
		}
		
		if(add_more_img_box) {
			txt = '';
			txt+= '<div class="picture" id="pictureDiv'+idW+'" style="text-align: center;" >';
					txt+= '<img id="'+image_box_id+'_'+idW+'" src="'+site_url+'img/'+default_img+'" alt="image" style="cursor: default" />';
					txt+= '<span id="lnk_'+idW+'"><a class="upload" id="'+image_box_id+idW+'" style="cursor:pointer;cursor:hand" >BROWSE</a></span>';
					//txt+= '<input type="hidden" id="img_hid_watch'+idW+'" name="src_img['+(idW-1)+']" value="" /> ';
			txt+= '</div>';
			
			document.getElementById("holderImg_"+img_id).appendChild(element);
					
			mySpan = document.getElementById("holderImg_"+myCounterImg);		
			mySpan.innerHTML = txt;
		}
		
		var button = $('#img'+idW), interval;
		var id = img_nr;	
		new AjaxUpload(button, {
			action: site_url + 'ajax/' + ajax_function + '/' + Math.random(10000), 
			
			data: {
				extraType : img_nr,
				item: folder_id,
				user: uid
			  },
			
			onSubmit : function(file, ext){
			   if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
					// extension is not allowed
					alert('Error: invalid file extension');
					// cancel upload
					return false;
				}

				button.text('BROWSE');
				this.disable();	
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13){
						button.text(text);
					} else {
						button.text('Uploading');
					}
				}, 200);
			},
			onComplete: function(file, response) {
				window.clearInterval(interval);	
				this.enable();
				if(response == 'error_size') {
					button.text('BROWSE');
					msg = document.getElementById('upload_file_size_exceeded').value;
					alert(msg);							
				}
				else if(response == 'error_ext') {
					button.text('BROWSE');
					msg = document.getElementById('upload_unsupported_extension').value;
					alert(msg);							
				}
				else {
					var myRez = response.split("!!!");
					var rez = myRez[0]+'?'+(new Date()).getTime();
					document.getElementById('img_'+id).src = rez;
					add_delete = '<a href="#" id="img'+idW+'" class="upload" onclick ="delete_edit_interview_image_box('+ uid+',\''+img_type+'\','+id+',\'pictureDiv'+idW+'\','+folder_id+'); return false;"> DELETE</a>';
					$("#lnk_"+id).html(add_delete);
					if(add_more_img_box) {
						edit_interview_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id);
					}
				}
			}
		});
	}
	
	function delete_edit_interview_image_box(uid,img_type,img_id,div_id,folder_id) {
		if(img_id == last_img) {
			last_img -- ;
		}		
		if(img_type != '') {
			params = 'img_type='+encodeURIComponent(img_type)+'&img_id='+encodeURIComponent(img_id)+ '&uid='+encodeURIComponent(uid)+'&folder_id='+encodeURIComponent(folder_id);
			httpObject = getXMLHTTPObject();
			httpObject.open('POST', site_url + 'ajax/delete_image_generic_way/' + Math.random(10000), true);
			httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			httpObject.setRequestHeader("Content-length", params.length);
			httpObject.setRequestHeader("Connection", "close");
			httpObject.onreadystatechange = function() {
				if (httpObject.readyState == 4) {
					if(httpObject.responseText == 'success') {
						$("#"+div_id).remove();
					}
					else {
						alert('There was an error! Please refresh the page and try again.');
					}
				}
			};
			httpObject.send(params);		
		}
		
	}
	
	function create_new_blogger_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id) {
		mcharity_img_nr;
		mcharity_img_nr++;
		myCounterCharityImg = mcharity_img_nr;
		idW = myCounterCharityImg;				
		
		if(img_id == 0 ) {    // if we don't have an image id 
			img_id = mcharity_img_nr;
		}
		
		try {
			element = document.createElement("span");
			element.id = "mcharity_holderImg_"+myCounterCharityImg;			
		}
		catch (e) {
			element = document.createElement("span");
			element.setAttribute("id", "mcharity_holderImg_"+myCounterCharityImg);
		}
		
		if(add_more_img_box) {
			txt = '';
			txt+= '<div class="picture" id="mcharity_pictureDiv'+idW+'" style="text-align: center;" >';
					txt+= '<img id="'+image_box_id+'_'+idW+'" src="'+site_url+'img/'+default_img+'" alt="image" style="cursor: default" />';
					txt+= '<span id="mcharity_lnk_'+idW+'"><a class="upload" id="'+image_box_id+idW+'" style="cursor:pointer;cursor:hand" >BROWSE</a></span>';
					//txt+= '<input type="hidden" id="img_hid_watch'+idW+'" name="src_img['+(idW-1)+']" value="" /> ';
			txt+= '</div>';
			
			document.getElementById("mcharity_holderImg_"+img_id).appendChild(element);
					
			mySpan = document.getElementById("mcharity_holderImg_"+myCounterCharityImg);		
			mySpan.innerHTML = txt;
		}
		
		var button = $('#img_more_charity'+idW), interval;
		var id = mcharity_img_nr;	
		new AjaxUpload(button, {
			action: site_url + 'ajax/' + ajax_function + '/' + Math.random(10000), 
			
			data: {
				extraType: id,
				celebrity_id: folder_id 
			  },
			
			onSubmit : function(file, ext){
			   if (! (ext && /^jpg$/.test(ext))) {
					// extension is not allowed
					alert('Error: invalid file extension');
					// cancel upload
					return false;
				}

				button.text('BROWSE');
				this.disable();	
				interval = window.setInterval(function() {
					var text = button.text();
					if (text.length < 13){
						button.text(text);
					} else {
						button.text('Uploading');
					}
				}, 200);
			},
			onComplete: function(file, response) {
				if(ajax_function == 'upload_blogger_charity_more_picture_edit') {
					more_blogger_charity_img++;
					if(more_blogger_charity_img < 2 ) {
						more_blogger_charity_img = 2;
					} 
				}
				window.clearInterval(interval);	
				this.enable();
				if(response == 'error_size') {
					button.text('BROWSE');
					msg = document.getElementById('upload_file_size_exceeded').value;
					alert(msg);							
				}
				else if(response == 'error_ext') {
					button.text('BROWSE');
					msg = document.getElementById('upload_unsupported_extension').value;
					alert(msg);							
				}
				else {
					var myRez = response.split("!!!");
					var rez = myRez[0]+'?'+(new Date()).getTime(); 
					document.getElementById('img_more_charity_'+id).src = rez;
					add_delete = '<a href="#" id="img_more_charity'+idW+'" class="upload" onclick ="delete_more_charity_image_box('+ uid+',\''+img_type+'\','+id+',\'mcharity_pictureDiv'+idW+'\','+folder_id+'); return false;"> DELETE</a>';
					$("#mcharity_lnk_"+id).html(add_delete);
					if(add_more_img_box) {
						create_new_blogger_upload_image_box(image_box_id,default_img,img_id,add_more_img_box,ajax_function,uid,img_type,folder_id);
					}
				}
			}
		});
	}
	
	function getAJAX(){
	var page_request = false;
	if (window.XMLHttpRequest){
		page_request = new XMLHttpRequest();
		return page_request;
	}
	else if (window.ActiveXObject){
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
			return page_request;
		}catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
				return page_request;
			}catch (e){
				return false;
			}
		}
	}else{
		return false;
	}
}

function show(show, hide){
	var show_element = document.getElementById(show);
	var hide_element = document.getElementById(hide);
	show_element.style.display = "block";
	hide_element.style.display = "none";
}

function checkEmail(email){
	var my_email = document.getElementById(email).value;
	if(!my_email.match(/^[a-zA-Z0-9_.]+@[a-zA-Z0-9_.]+\.[a-zA-Z0-9_.]+$/g)){
		id = 0;
		
	}else{
		id = 1;
	}
	return id;
}


function validateForm(){
	var ajax = getAJAX();
	var url = site_url+"ajax/check_membership_request/" + Math.random(10000);
	var val = 0; 
	var email = document.getElementById('email').value;
	ajax.onreadystatechange = function() {
		if (ajax.readyState == 4 && (ajax.status == 200 || window.location.href.indexOf("http") == -1)) {
				
				if($('input[name=first_name]').val() == ''){
					$('input[name=first_name]').next('span').html($('input[name=error_first_name]').val());
					val++;
				}else{
					$('input[name=first_name]').next('span').html('');
				}
				if($('input[name=last_name]').val() == ''){
					$('input[name=last_name]').next('span').html($('input[name=error_last_name]').val());
					val++;
				}else{
					$('input[name=last_name]').next('span').html('');
				}
				if($('input[name=email]').val() == ''){
					$('input[name=email]').next('span').html($('input[name=error_email_missing]').val());
					val++;
				}else{
					email = $('input[name=email]').val();
					if(checkEmail('email') == 0){
						$('input[name=email]').next('span').html($('input[name=error_email_valid]').val());
						val++;
					}else{
						if(ajax.responseText == 0){
							$('input[name=email]').next('span').html($('input[name=error_email_exists]').val());
							val++;
						}else{
							$('input[name=email]').next('span').html('');
						}
					}
				}
				if(val == 0){
					document.join.submit();
				}else{
					
				}
				
		}
	}
	parametrii = "validateForm=" + email;
	ajax.open('POST', url, true);
	ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	ajax.setRequestHeader("Content-length", parametrii.length);
	ajax.setRequestHeader("Connection", "close");
	ajax.send(parametrii);

}


function show_membership_request() {
	//$('#request_membership_btn').css('display', 'none');
	$('#request_membership_div').css('display', 'block');
}

	function js_request_membership_check() {
		var validator = $("#request_membership").validate({
			rules: {				
				first_name:  {
					required: true,
					minlength: 2
				},
				last_name:  {
					required: true,
					minlength: 2
				},				
				email: {
					required: true,
					email: true ,
					remote: {
						url: site_url+"ajax/check_membership_request/" + Math.random(10000),
						type: "post",
						data: {
							email: function() {
							return $("#email").val();
							}
						}
					}				
				},
				captcha_test: {
					required: true,
					remote: {
						url: site_url+"ajax/captcha_check/" + Math.random(10000),
						type: "post",
						data: {
							captcha_code: function() {
								return $("#captcha_test").val();
							}
						}
					}
				}
			},
			messages: {
				email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("This email is already in use")
				},
				captcha_test: {
					required: "Please enter a valid code",
					minlength: "Please enter a valid code",
					remote: jQuery.format("This captcha code is wrong. Try again!")
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.parent().next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#request_membership_final_btn").click(function() {
			if(validator.form()) {
				$("#request_membership").submit();
			}
		});
	}
	
	function js_request_membership_check_login() {
		var validator = $("#request_membership").validate({
			rules: {				
				first_name:  {
					required: true,
					minlength: 2
				},
				last_name:  {
					required: true,
					minlength: 2
				},				
				email: {
					required: true,
					email: true ,
					remote: {
						url: site_url+"ajax/check_membership_request/" + Math.random(10000),
						type: "post",
						data: {
							email: function() {
							return $("#email").val();
							}
						}
					}				
				},
				captcha_test: {
					required: true,
					remote: {
						url: site_url+"ajax/captcha_check/" + Math.random(10000),
						type: "post",
						data: {
							captcha_code: function() {
								return $("#captcha_test").val();
							}
						}
					}
				}
			},
			messages: {
				email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("This email is already in use")
				},
				captcha_test: {
					required: "Please enter a valid code",
					minlength: "Please enter a valid code",
					remote: jQuery.format("This captcha code is wrong. Try again!")
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.parent().next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#request_membership_final_btn").click(function() {
			if(validator.form()) {
				$("#request_membership").submit();
			}
		});
	}
	
	function js_register_membership_check() {
		var d = new Date();
		var an = d.getFullYear();
		var validator = $("#register").validate({
			errorElement: 'p',
			rules: {
				username: {
					required: true,
					minlength: 2,
					remote: {
						url: site_url+"ajax/check_membership_request_username/" + Math.random(10000),
						type: "post",
						data: {
							username: function() {
							return $("#username").val();
							}
						}
					}
				},
				first_name:  {
					required: true,
					minlength: 1
				},
				last_name:  {
					required: true,
					minlength: 1
				},
				password: {
					required: true,
					minlength: 6
				},
				confirm_password: {
					required: true,
					minlength: 6,
					equalTo: "#password"
				},
				email: {
					required: true,
					email: true ,
					remote: {
						url: site_url+"ajax/check_membership_request/" + Math.random(10000),
						type: "post",
						data: {
							email: function() {
							return $("#email").val();
							}
						}
					}				
				},
				confirm_email: {
					required: true,
					minlength: 5,
					equalTo: "#email"
				},
				month: {
					number: true,
					range: [1, 12]
				},
				day: {
					number: true,
					range: [1, 31]
				},
				year: {
					number: true,
					range: [1900, an]
				},
				zip_code: {
					required: true,
					minlength: 1
				},
				agree: {
					required: true
				}
			},
			messages: {
				username: {
					remote: jQuery.format("This username is already in use")
				},
				email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("This email is already in use")
				},
				captcha_test: {
					required: "Please enter a valid code",
					minlength: "Please enter a valid code",
					remote: jQuery.format("This captcha code is wrong. Try again!")
				},
				agree: {
					required: "You must agree with I-ELLA's Terms of Service "
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#register_btn").click(function() {
			if(validator.form()) {
				$("#register").submit();
			}
		});
	}
	
	function js_register_membership_check_with_code() {
		var d = new Date();
		var an = d.getFullYear();
		var validator = $("#register").validate({
			errorElement: 'p',
			rules: {
				username: {
					required: true,
					minlength: 2,
					remote: {
						url: site_url+"ajax/check_membership_request_username/" + Math.random(10000),
						type: "post",
						data: {
							username: function() {
							return $("#username").val();
							}
						}
					}
				},
				first_name:  {
					required: true,
					minlength: 1
				},
				last_name:  {
					required: true,
					minlength: 1
				},
				password: {
					required: true,
					minlength: 6
				},
				confirm_password: {
					required: true,
					minlength: 6,
					equalTo: "#password"
				},
				email: {
					required: true,
					email: true ,
					remote: {
						url: site_url+"ajax/check_membership_request/" + Math.random(10000),
						type: "post",
						data: {
							email: function() {
							return $("#email").val();
							}
						}
					}				
				},
				confirm_email: {
					required: true,
					minlength: 5,
					equalTo: "#email"
				},
				month: {
					number: true,
					range: [1, 12]
				},
				day: {
					number: true,
					range: [1, 31]
				},
				year: {
					number: true,
					range: [1900, an]
				},
				zip_code: {
					required: true,
					minlength: 1
				},
				agree: {
					required: true
				},
				promo_code: {
					required: true,
					minlength: 4,
					remote: {
						url: site_url+"ajax/check_register_promo_code/" + Math.random(10000),
						type: "post",
						data: {
							promo_code_val: function() {
							return $("#promo_code").val();
							}
						}
					}
				}
			},
			messages: {
				username: {
					remote: jQuery.format("This username is already in use")
				},
				email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("This email is already in use!")
				},
				captcha_test: {
					required: "Please enter a valid code",
					minlength: "Please enter a valid code",
					remote: jQuery.format("This captcha code is wrong. Try again!")
				},
				agree: {
					required: "You must agree with I-ELLA's Terms of Service "
				},
				promo_code: {
					remote: jQuery.format("This promo code doesn't exist or has expired!")
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#register_btn").click(function() {
			if(validator.form()) {
				$("#register").submit();
			}
		});
	}
	
	
	function recover_password_form_check() {
		var validator_recover_pass = $("#myRecoverPassFrm").validate({
			rules: {												
				recover_email: {
					required: true,
					email: true ,
					remote: {
						url: site_url+"ajax/check_recover_password_email/" + Math.random(10000),
						type: "post",
						data: {
							email: function() {
							return $("#recover_email").val();
							}
						}
					}				
				}
			},
			messages: {
				recover_email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("There is no account associated with this email!")
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.parent().next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#myRecoverPassBtn").click(function() {
			if(validator_recover_pass.form()) {
				$("#myRecoverPassFrm").submit();
			}
		});
	}
	
	function change_password_form_check() {
		var validator_recover_pass = $("#myChangePassFrm").validate({
			rules: {
				username_pass: {
					required: true
				},
				old_password: {
					required: true
				},
				new_password: {
					required: true,
					minlength: 6
				},
				repeat_new_password: {
					required: true,
					minlength: 6,
					equalTo: "#new_password"
				}
			},
			messages: {
				recover_email: {
					required: "Please enter a valid email address",
					minlength: "Please enter a valid email address",
					remote: jQuery.format("There is no account associated with this email!")
				}
			},

			// the errorPlacement has to take the table layout into account
			errorPlacement: function(error, element) {
				if ( element.is(":radio") )
					error.appendTo( element.parent().next().next() );
				else if ( element.is(":checkbox") )
					error.appendTo ( element.next() );
				else
					error.appendTo( element.parent() );
			},
			// set this class to error-labels to indicate valid fields
			success: function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});
		$("#myChangePassBtn").click(function() {
			if(validator_recover_pass.form()) {
				$("#myChangePassFrm").submit();
			}
		});
	}
	
	function generate_new_captche_code() {
		//Get a reference to CAPTCHA image
		img = document.getElementById('img_captcha'); 
		//Change the image
		var new_img = site_url+"ajax/generate_new_captcha/"+Math.random(10000);
		img.src = new_img;
		$("#captcha_test").val('');
	}

function popupCreditInfo() {
	httpObject = getXMLHTTPObject();
	httpObject.open('GET', site_url + '/ajax/credit_info_popup/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', '158px').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				
			});
			Custom.init();
		}
	};
	httpObject.send(null);
}

function popupVerificationProccessInfo() {
	httpObject = getXMLHTTPObject();
	httpObject.open('GET', site_url + '/ajax/verification_proccess_popup/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', '158px').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				
			});
			Custom.init();
		}
	};
	httpObject.send(null);
}

function popupTerms() {
	httpObject = getXMLHTTPObject();
	httpObject.open('GET', site_url + '/ajax/terms_popup/' + Math.random(10000), true);
	httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	httpObject.setRequestHeader("Connection", "close");
	
	httpObject.onreadystatechange = function() {
		if (httpObject.readyState == 4) {
			$('#shopping-cart-popup-content').html(httpObject.responseText);
			$('<br />').css('clear', 'both').appendTo('#shopping-cart-popup-content');
			$('#lightbox_bg').show();
			$('#shopping-cart-popup').css('top', '158px').fadeIn('fast');
			$('html, body').animate({scrollTop: $('#header').height()}, 'slow');
		    $('#continue_link').bind('click', function() {
				
			});
			Custom.init();
		}
	};
	httpObject.send(null);
}


	function ship_swap(swid) {
		params = 'swid='+encodeURIComponent(swid);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/ship_swap/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					window.location.reload();
				}
				else {
					alert('There was an error! Please refresh the page and try again.');
				}
			}
		};
		httpObject.send(params);
	}
	
	function ship_item(item_id) {
		params = 'item_id='+encodeURIComponent(item_id);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/ship_item/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					window.location.reload();
				}
				else {
					alert('There was an error! Please refresh the page and try again.');
				}
			}
		};
		httpObject.send(params);
	}
	
	function check_items_from_cart(cart_id){
		params = 'cart_id='+encodeURIComponent(cart_id);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/check_items_from_cart/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
				if(httpObject.responseText == 'success') {
					$('#paypal_form_0').submit();
				}
				else {
					window.location.href = site_url + 'checkout/step/3';
				}
			}
		};
		httpObject.send(params);
	}
	
	function change_celeb_item_active_status(celeb_item) {
		params = 'celeb_item='+encodeURIComponent(celeb_item);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/change_celeb_item_active_status/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {				
			}
		};
		httpObject.send(params);
	}
	
	function update_state(class_text, field_name, country_id, mode){
		params = 'class='+encodeURIComponent(class_text)+'&field_name='+encodeURIComponent(field_name)+'&country_id='+encodeURIComponent(country_id);
		httpObject = getXMLHTTPObject();
		httpObject.open('POST', site_url + 'ajax/change_state_field/' + Math.random(10000), true);
		httpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpObject.setRequestHeader("Content-length", params.length);
		httpObject.setRequestHeader("Connection", "close");
		httpObject.onreadystatechange = function() {
			if (httpObject.readyState == 4) {
					if (mode == "") {
						document.getElementById('state_replace').innerHTML = httpObject.responseText;
					}
					if(mode == 'edit'){
						document.getElementById('state_replace_edit').innerHTML = httpObject.responseText;
					}
			}
		};
		httpObject.send(params);
	}	
