Event.observe(window, 'load', function() {
	BBArticle.onLoad();
});

var BBArticle = {
	book: {},
	music: {},
	movie: {},
	game: {},
	comic: {},
	Types: ['book','music','movie','game','comic'],
	BookDescIsGuided: true,
	nrofimages: 0,
	uploadedImages: [],
	IsEdit: false,
	onLoad: function() {
		if (this.IsEdit) {
			for(var i=0; i<this.ImageData.length; i++) {
				this.addImage(this.ImageData[i]);
			}
			if ((this.currentType=='book' || this.currentType=='comic') && ($F(this.currentType+'-input-standard_number')!='') && (!this.VerifyISBN($F(this.currentType+'-input-standard_number')))) {
				$(this.currentType+'-input-standard_number').focus();
				$(this.currentType+'-label-standard_number').className='error';
				alert('ISBN-numret i annonsen är felaktigt formaterat.\nVar god formatera ISBN-numret enligt följande:\n\n * Ange bara siffror, 10 eller 13 stycken.\n * ISBN-numret kan innehålla ett X på slutet.\n * Ange inte texten ISBN.\n * Ange inga mellanslag eller avstavningstecken.\n\nDu kan också välja att lämna ISBN-fältet tomt.');
				return false;
			} else this.setStep2();
		}
	},
	Edit: function(mainCat, id) {
		window.location.href='page-start?article=edit&maincat='+mainCat+'&id='+id;
	},
	Delete: function(ref, mainCat, id, title) {
		$(ref).setStyle({'backgroundColor':'#faa'});
		if (confirm("Är du säker på att du vill ta bort annonsen\n'"+unescape(title)+"'?")) {
			window.location.href='callbacks/article.php?formaction=delete&maincat='+mainCat+'&id='+id;
		} else {
			$(ref).setStyle({'backgroundColor':''});
		}
	},
	ShowHide: function(divName, visible) {
		if ($(divName)==undefined) {
			alert('div "'+divName+'" saknas');
		} else {
			if (visible) $(divName).show();
			else $(divName).hide();
		}
	},
	ChangeType: function(type) {
		this.currentType=type;
		for (var i=0; i<this.Types.length; i++) {
			this.ShowHide('article-form-'+this.Types[i], this.Types[i]==type);
		}
		BBArticle.setDefaultImage();
	},
	SetBookDescGuided: function(enabled) {
		this.BookDescIsGuided=enabled;
		if (enabled) {
			$('book-description-guided').show();
			$('book-tr-description').hide();
		} else {
			var d=this.GetGuidedText();
			if (d!="") $('book-input-description').value = d;
			$('book-description-guided').hide();
			$('book-tr-description').show();
		}
	},
	GetGuidedText: function() {
		var s="";
		for(var i=0; i<this.GuideFields.length; i++) {
			var inpId=this.GuideFields[i]["inputId"];
			var v=$F(inpId);
			switch (inpId) {
				case "input-edition":
					if (v!="") s+=v + " uppl. ";
				break;
				case "input-pages":
					if (v!="") s+=v + " s. ";
				break;
				case "input-formatheight":
					if (v!="") s+=v +"x"+$F("input-formatwidth") + "cm. ";
				break;
				case "input-formatwidth":
					// Ignore
				break;
				case "input-weight":
					if (v!="") s+=v+" gram. ";
				break;
				case "input-protective_cover":
					if (v!="") s+="Skyddsomslag "+v+". ";
				break;
				default:
					if (v!="") {
						s+=v+". ";
						//s+=this.GuideFields[i]["description"]+": "+v+". ";
					}
			}
		}
		return s;
	},
	VerifyStep1: function () {
		if (!this.IsEdit) {
			if (this.currentType=='book') {
				var d=this.GetGuidedText();
				if (d!="") $('book-input-description').value = d;
			}
			$('input-action').value='new_book';
		} else {
			$('input-action').value='edit_book';
		}
		$('new_article_form').action='callbacks/article.php'; /* Funkar inte i ie6 */
		$('new_article_form').enctype='multipart/form-data';
		var ok=true;
		var errorFieldNames = '';
		for (var i=0; i<this[this.currentType].MandatoryFieldsStep1.length; i++) {
			var mandatoryFieldName=this[this.currentType].MandatoryFieldsStep1[i];
			if ($F(this.currentType+'-input-'+mandatoryFieldName)=="") {
				if ((mandatoryFieldName=="description") && (this.currentType=='book')) {
					$('book-label-description-guided').className='error';
				}
				if (ok) $(this.currentType+'-input-'+mandatoryFieldName).focus();
				$(this.currentType+'-label-'+mandatoryFieldName).className='error';
				ok=false;
				
				var label = $(this.currentType+'-label-'+mandatoryFieldName);
				var fName="";
				if (label!=null) fName=label.textContent?label.textContent:label.innerHTML; 
				if (fName=="") fName=mandatoryFieldName; 
				errorFieldNames+=' - '+fName+'\n';
			}
		}
		if (ok) {
			if ((this.currentType=='book' || this.currentType=='comic') && ($F(this.currentType+'-input-standard_number')!='') && (!this.VerifyISBN($F(this.currentType+'-input-standard_number')))) {
				// Lets help the user by removing "-" and " " from the ISBN number
				var tempisbn = $F(this.currentType+'-input-standard_number');
				var strippedIsbn = tempisbn.replace(/[\s-]/g, ''); 
				if ((strippedIsbn!=tempisbn) && (this.VerifyISBN(strippedIsbn))) {
					$(this.currentType+'-input-standard_number').value=strippedIsbn;
				}
			}
			
			if (!this.IsNumeric($F(this.currentType+'-input-price'))) {
				$(this.currentType+'-input-price').focus();
				$(this.currentType+'-label-price').className='error';
				alert('Du måste ange ett pris för din annons.');
				return false;
			} else if ((this.currentType=='book' || this.currentType=='comic') && ($F(this.currentType+'-input-standard_number')!='') && (!this.VerifyISBN($F(this.currentType+'-input-standard_number')))) {
				$(this.currentType+'-input-standard_number').focus();
				$(this.currentType+'-label-standard_number').className='error';
				alert('Det ISBN-nummer du anger måste vara formaterat enligt följande:\n\n * Ange bara siffror, 10 eller 13 stycken.\n * ISBN-numret kan innehålla ett X på slutet.\n * Ange inte texten ISBN.\n * Ange inga mellanslag eller avstavningstecken.\n\nDu kan också välja att lämna ISBN-fältet tomt.');
				return false;
			} else {
				if ($F(this.currentType+'-input-price')<0) {
					$(this.currentType+'-input-price').focus();
					$(this.currentType+'-label-price').className='error';
					alert('Du har satt ett felaktigt pris på din annons.');
					return false;
				} else {
					if ($F(this.currentType+'-input-uniqueidentifier')!="") {
						var extra="";
						if (this.IsEdit) {
							extra+="&maincat="+$F('input-main-cat')+"&id="+$F('book-input-id');
						}
						new Ajax.Request('callbacks/article.php?formaction=verify_unique_identifier&unique_identifier='+$F(this.currentType+'-input-uniqueidentifier')+extra, 
							{'onSuccess':this.onVerifyUniqueIdentifierSuccess.bind(this),
							 'onFailure':this.onVerifyUniqueIdentifierFailure.bind(this)}
						);
						return false;
					} else return true;
				}
			}
		} else {
			if (errorFieldNames=='') {
				alert('Du måste fylla i alla obligatoriska fält.\nDe fält du har missat har markerats med rött.');
			} else {
				alert('Du måste fylla i alla obligatoriska fält.\nDe fält du har missat har markerats med rött.\n\nFöljande fält måste fyllas i:\n'+errorFieldNames);
			}
			return false;
		}
	},
	onVerifyUniqueIdentifierFailure: function(response) {
		alert('Ett fel uppstod när servern anropades. Var god försök igen om en stund.');
	},
	onVerifyUniqueIdentifierSuccess: function(response) {
		var res = response.responseJSON;
		
		if (res==null) {
			alert('Tyvärr uppstod ett fel när servern anropades. Var god försök igen om en stund.\n\nMeddelande:\n'+response.responseText);
		} else if (res.error!=undefined) {
			alert(res.error);
		} else {
			if (res.message==undefined) {
				this.setStep2();
			} else {
				$(this.currentType+'-input-uniqueidentifier').focus();
				$(this.currentType+'-label-uniqueidentifier').className='error';
				alert(res.message);
			}
		}
		
	},
	Step2: function() {
		if (this.VerifyStep1()) this.setStep2();
	},
	addImage: function(iData) {
		if (typeof(console)!="undefined") console.log('addImage', iData);
		var imgUrl = "callbacks/article.php?formaction=existing_tmpimg&id="+iData.item_id+"&maincat="+iData.main_category+"&pictureindex="+iData.picture_index+"&crop="+((iData.do_crop==1)?'true':'false')+"&r="+Math.floor(Math.random()*1000);
		var img = new Element('img', {'src':imgUrl,'class':'preview_image'});
		var span = new Element('span', {'style':'cursor:hand;cursor:pointer;color:#aa3333;'});
		span.update('<img src="images/icon_delete_image.png"> Ta bort bilden');
		
		var br = new Element('br');
		var span2 = new Element('span', {'style':'cursor:hand;cursor:pointer;'});
		if (iData.do_crop==1) span2.update('   <img src="images/icon_crop_image.png"> Klipp inte bilden');
		else span2.update('   <img src="images/icon_crop_image.png"> Klipp bilden');
		
		var data = new Object();
		data.mainCat=this.currentType;
		data.fieldName='picture'+iData.picture_index;
		data.formId=null;

		data.img = img;
		data.cropSpan = span2;
		data.isCropping = (iData.do_crop==1);
		data.iData = iData;
		
		data.containerDiv = new Element('div',{'class':'preview_image_div'});
		$(this.currentType+'_images_container').appendChild(data.containerDiv);
		
		data.containerDiv.appendChild(img);
		data.containerDiv.appendChild(span);
		data.containerDiv.appendChild(br);
		data.containerDiv.appendChild(span2);
		
		Event.observe(span, 'click', BBArticle.removeImage.bindAsEventListener(this, data));
		Event.observe(span2, 'click', BBArticle.toggleCrop.bindAsEventListener(this, data));
		
		if (BBArticle.uploadedImages.length==0 /*data.fieldName=='picture1'*/) {
			$('article_image').src=imgUrl;
			data.isMainImage=true;
		} else data.isMainImage=false;
		
		BBArticle.uploadedImages.push(data);
		BBArticle.FieldChange(data.mainCat, data.fieldName, data.fieldType);
	},
	setStep2: function() {
		$(this.currentType+'-step-1').hide();
		$(this.currentType+'-step-2').show();
		if (!this.IsEdit) {
			$('type-selects').hide();
			$('header-step1').hide();
		}
		$(this.currentType+'-header2-step1').hide();
		$(this.currentType+'-header-step2').show();
		this.FillPreviewAd();
		$('article-form-book-preview-ad').show();
		scroll(0,0); /* Ej browsertestat */
		
		this.GetFee();/* Fyll i beställningsavgift */
		$(this.currentType+'-itemfee-container').show();
		if ($('article-edit-info-page-1')!=null) $('article-edit-info-page-1').hide();
		if ($('article-edit-info-page-2')!=null) $('article-edit-info-page-2').show();
		
		if ($(this.currentType+'-edit-info-page-1')!=null) $(this.currentType+'-edit-info-page-1').hide();
		if ($(this.currentType+'-edit-info-page-2')!=null) $(this.currentType+'-edit-info-page-2').show(); 
		
	},
	Step1: function() {
		$(this.currentType+'-step-2').hide();
		$(this.currentType+'-header-step2').hide();
		$(this.currentType+'-step-1').show();
		$(this.currentType+'-header2-step1').show();
		if (!this.IsEdit) $('type-selects').show();
		$('article-form-book-preview-ad').hide();
		$(this.currentType+'-itemfee-container').hide();
		
		if ($('article-edit-info-page-1')!=null) $('article-edit-info-page-1').show();
		if ($('article-edit-info-page-2')!=null) $('article-edit-info-page-2').hide();
		
		if ($(this.currentType+'-edit-info-page-1')!=null) $(this.currentType+'-edit-info-page-1').show();
		if ($(this.currentType+'-edit-info-page-2')!=null) $(this.currentType+'-edit-info-page-2').hide(); 
	},
	AjaxFileUpload: function(formId, mainCat, fieldName, fieldType) {
		if (this.CountImages()>=9) {
			alert('Kan tyvärr inte ladda upp ytterligare en bild.\nEn artikel kan ha max 9 bilder.\n\nVill du ersätta en bild, ta först bort den och ladda sedan upp en ny.');
			return false;
		} else {
			fieldName = Math.floor(Math.random()*9000)+1000;
			if (typeof(console)!="undefined") console.log('fieldName',fieldName);
			var c = {
				'onComplete': this.ajaxUploadComplete.bind(this, {'mainCat': mainCat, 'fieldName': fieldName, 'fieldType': fieldType, 'formId': formId})
			}
			$("picture_key_"+formId).value=fieldName;
			$("tempid_"+formId).value=this[this.currentType].TempID;
			$("action_"+formId).value="ajaxfile";
			if (AIM.submit($(formId), c)) {
				$(formId).setAttribute('action','callbacks/article.php');
				$(formId).submit();
			}
			Util.ShowLoading($(this.currentType+'-input-picture1'));
		}
	}, 
	removeImage: function(event, data) {
		data.isDeleted = true;
		data.containerDiv.remove();
		
		if (data.fieldName=='picture1') {
			BBArticle.setDefaultImage();
		}
		BBArticle.GetFee();
	},
	setDefaultImage: function() {
		switch(this.currentType) {
			case "book": $('article_image').src="images/no_image_1.jpg"; break;
			case "music": $('article_image').src="images/no_image_2.jpg"; break;
			case "movie": $('article_image').src="images/no_image_3.jpg"; break;
			case "game": $('article_image').src="images/no_image_4.jpg"; break;
		}
	},
	toggleCrop: function(event, data) {
		data.isCropping = !data.isCropping;
		if (data.iData!=undefined) {
			// Special treatment for already uploaded images
			var imgUrl = "callbacks/article.php?formaction=existing_tmpimg&id="+data.iData.item_id+"&maincat="+data.iData.main_category+"&pictureindex="+data.iData.picture_index+"&crop="+((data.isCropping)?'true':'false')+"&r="+Math.floor(Math.random()*1000);
		} else {
			var imgUrl = "callbacks/article.php?formaction=tmpimg&tempid="+this[this.currentType].TempID+"&name="+data.fieldName+"&crop="+((data.isCropping)?'true':'false')+"&r="+Math.floor(Math.random()*1000);
		}
		if (data.isCropping) {
			data.cropSpan.update('   <img src="images/icon_crop_image.png"> Klipp inte bilden');
		} else {
			data.cropSpan.update('   <img src="images/icon_crop_image.png"> Klipp bilden');
		}
		data.img.setAttribute("src",imgUrl);
		if (data.fieldName=='picture1' || data.isMainImage==true) $('article_image').src = imgUrl;
	},
	ajaxUploadComplete: function(iData) {
		Util.HideLoading();
		var iframe = $($(iData.formId).getAttribute('target'));
		
		if (iframe.contentDocument!=undefined) {
			// contentDocument for firefox
			var result = iframe.contentDocument.body.innerHTML;
		} else {
			// contentWindow for explorer
			var result = iframe.contentWindow.document.body.innerHTML;
		}
		try {
			res = result.evalJSON();
		} catch (err) {
			res = null;
		}
		if (res==null) {
			alert('Något gick fel när filen skulle laddas upp.\n\n'+result);
		} else  if (res.error!=undefined) {
			alert('Kunde inte ladda upp bilden.\n\n'+res.error);
		} else {
			var data = new Object();
			
			var imgUrl = "callbacks/article.php?formaction=tmpimg&tempid="+this[this.currentType].TempID+"&name="+iData.fieldName+"&crop=true&r="+Math.floor(Math.random()*1000);
			data.img = new Element('img', {'src':imgUrl,'class':'preview_image'});
			data.span = new Element('span', {'style':'cursor:hand;cursor:pointer;color:#aa3333;'});
			data.span.update('<img src="images/icon_delete_image.png"> Ta bort bilden');
			
			data.br = new Element('br');
			data.span2 = new Element('span', {'style':'cursor:hand;cursor:pointer;'});
			data.span2.update('   <img src="images/icon_crop_image.png"> Klipp inte bilden');
			
			data.cropSpan = data.span2;
			data.isCropping = true;
			
			data.containerDiv = new Element('div',{'class':'preview_image_div'});
			$(this.currentType+'_images_container').appendChild(data.containerDiv);
			
			data.containerDiv.appendChild(data.img);
			data.containerDiv.appendChild(data.span);
			data.containerDiv.appendChild(data.br);
			data.containerDiv.appendChild(data.span2);
			
			data.mainCat=this.currentType;
			data.fieldName=iData.fieldName;
			data.formId=null;

			//data.iData = iData;
			
			
			Event.observe(data.span, 'click', BBArticle.removeImage.bindAsEventListener(this, data));
			Event.observe(data.span2, 'click', BBArticle.toggleCrop.bindAsEventListener(this, data));
			
			if (BBArticle.uploadedImages.length==0 /*data.fieldName=='picture1'*/) {
				$('article_image').src=imgUrl;
				data.isMainImage=true;
			} else data.isMainImage=false;
			BBArticle.uploadedImages.push(data);
			BBArticle.FieldChange(data.mainCat, data.fieldName, data.fieldType);
			
			BBArticle.GetFee();
		}
	},
	FieldChange: function(mainCat, fieldName, fieldType) {
		switch(fieldType) {
			case 'ajaxfile':
				// Do nothing here
			break;
			case 'checkbox':
				switch(fieldName) {
					case 'sponsoredsearch': this.GetFee(); break;
				}
			break;
		}
	},
	Submit: function(ref) {
		// Build images data object array to provide for the server as a json-object
		var imagesData = new Array();
		for (var i=0; i<BBArticle.uploadedImages.length; i++) {
			var imgData = new Object();
			if (BBArticle.uploadedImages[i].iData) {
				// This is an old image
				imgData.is_deleted = BBArticle.uploadedImages[i].isDeleted==true;
				imgData.is_new = false;
				imgData.do_crop = BBArticle.uploadedImages[i].isCropping;
				imgData.id = BBArticle.uploadedImages[i].iData.id;
				imgData.item_id = BBArticle.uploadedImages[i].iData.item_id;
				imgData.picture_index =  BBArticle.uploadedImages[i].iData.picture_index;
				
				imagesData.push(imgData);
			} else {
				if (BBArticle.uploadedImages[i].isDeleted!=true) {
					imgData.is_deleted = false;
					imgData.is_new = true;
					imgData.picture_key = BBArticle.uploadedImages[i].fieldName;
					imgData.do_crop = BBArticle.uploadedImages[i].isCropping;
					
					imagesData.push(imgData);
				}
			}
		}
		var o = {
			'picturedata': imagesData,
			'sponsoredsearch': $(this.currentType+'-input-sponsoredsearch').checked,
			'itemfee': $(this.currentType+'-itemfee').innerHTML
		}
		$(this.currentType+'_formdata').value = Object.toJSON(o);
		$(ref).disable();
		if (Util!=undefined) Util.ShowLoading($(ref), 'Var god vänta, sparar din annons');
		$('form_'+this.currentType+'_step_1').submit();
	},
	IsNumeric: function(sText)
	{
	   var ValidChars = "0123456789.";
	   var IsNumber=true;
	   var Char;
	   
	   if (sText.length==0) IsNumber=false;
	 
	   for (i = 0; i < sText.length && IsNumber == true; i++) 
	      { 
	      Char = sText.charAt(i); 
	      if (ValidChars.indexOf(Char) == -1) 
	         {
	         IsNumber = false;
	         }
	      }
	   return IsNumber;
   },
   FillPreviewAd: function()
   {
   	$('article-form-book-preview-ad-title').innerHTML=$F(this.currentType+'-input-title');
   	if ($(this.currentType+'-input-standard_number')!=null) $('article-form-book-preview-ad-isbn').innerHTML='ISBN: ' + $F(this.currentType+'-input-standard_number');
   	if ($(this.currentType+'-input-author')!=null) $('article-form-book-preview-ad-author').innerHTML=$F(this.currentType+'-input-author');
   	$('article-form-book-preview-ad-description').innerHTML=$F(this.currentType+'-input-description');
   	$('article-form-book-preview-ad-price').innerHTML=Math.floor(parseFloat($F(this.currentType+'-input-price'))) + " kr";
   },
   CountImages: function() {
  		BBArticle.nrofimages=0;
  		for (var i=0; i<BBArticle.uploadedImages.length; i++) if (BBArticle.uploadedImages[i].isDeleted!=true) BBArticle.nrofimages++;
  		return BBArticle.nrofimages; 
   },
   GetFee: function(){
   		$(this.currentType+'-itemfee').innerHTML = '?';
   		var bbprice = $F(this.currentType+'-input-price');
   		
   		var nrofimages = this.CountImages();
   		var bbsponsored = 0;
   		if($(this.currentType+'-input-sponsoredsearch').checked) bbsponsored = 1;
   		var mUrl 	= 'callbacks/article.php';
		var pbody	= 'formaction=itemfee&price=' + bbprice + '&nrofimages='+nrofimages + '&bbsponsored=' + bbsponsored;
		new Ajax.Updater(this.currentType+'-itemfee', 'callbacks/article.php', { 'method': 'post', 'postBody': pbody});
   		//alert('price:' + bbprice + ' images:' + nrofimages);
   },
   VerifyISBN: function(isbn) {
	   return isbn.match(/^((\d{10})|(\d{13})|(\d{9}[xX])|(\d{12}[xX]))$/);
   }
}