Ext.namespace('scancafe.share');
Ext.BLANK_IMAGE_URL = commonJsPath + 'yui-ext/resources/images/default/s.gif'

scancafe.share.gallery = function(config) {
	this.serverUrl = webRoot;
	this.baseUrl = this.serverUrl + 'extends/ajax/';
	this.shareImagesUrl = this.serverUrl + 'extends/includes/images/';
	Ext.apply(this, config);
	this.imageServerUrl = this.imageServerUrl || this.baseUrl;
	this.init();
};

scancafe.share.gallery.prototype = {
	cursor : 0,
	pageSize : 5,
	page : 0,
	imagesCount : 0,
	captionTpl : '{img} to {imgCount}',
	pagesCount : 0,
	buttons : {},
	imageUrl:'image.request.php',
	onImageLoad : function() {
	},
	init : function() {
		if (!this.captionTpl.compile) {
			this.captionTpl = new Ext.Template(this.captionTpl);
		}
		this.el = Ext
				.get(this.el)
				.update('<div id="slider-navigator" class="slider-navigator"></div>');
		var row1 = Ext.DomHelper.append(this.el, {
			tag : 'div',
			cls : 'top oh',
			children : [{
				tag : 'a',
				cls : 'fl',
				id : 'prev',
				title : 'Previous Image'
			}, {
				tag : 'span',
				cls : 'fl',
				id : 'pager-caption'
			}, {
				tag : 'a',
				cls : 'fr',
				title : 'Next Image',
				id : 'next'
			}]
		}, true);
		var row2 = Ext.DomHelper.append(this.el, {
			tag : 'div',
			cls : 'slider oh',
			children : [{
				tag : 'div',
				cls : 'previous',
				children : [{
					tag : 'a',
					id : 'prevPage',
					title : 'Previous Page'
				}, {
					tag : 'a',
					id : 'firstPage',
					title : 'First Page'
				}]
			}, {
				tag : 'div',
				id : 'idc-slider-thumbs-container',
				cls:'fl oh',
				children:[{
					tag:'ul',
					cls : 'thumbs',
					id : 'idc-slider-thumbs'
				}]
			}, {
				tag : 'div',
				cls : 'next',
				children : [{
					tag : 'a',
					id : 'nextPage',
					title : 'Next Page'
				}, {
					tag : 'a',
					id : 'lastPage',
					title : 'Last Page'
				}]
			}]
		}, true);
		this.el.select('a').elements.each(function(s) {
			this.buttons[s.id] = Ext.get(s);
			if (!this.buttons[s.id].hasClass('disabled')) {
				this.buttons[s.id].on('click', this.onClick.bind(this, s.id),
						this);
			}
		}.bind(this));
		this.sliderCaption = Ext.get(row1.child('span#pager-caption', true));
		this.sliderContainer = row2.child('ul');
		this.store = new Ext.data.JsonStore({
			url : this.baseUrl + 'image.slider.request.php',
			baseParams : {
				a : 'images',
				album_id : this.album_id
			},
			root : 'images',
			fields : ['id', 'filename', 'deleted', 'reconstructed_id', 'original_id',
					'reconstructed_price','is_reconstructed','rec_class_name','included',
					'position','is_defect','is_cover','is_paid'],
			totalProperty : 'imagesCount',
			id:'id'
		});
		this.slider = new Ext.View(
				this.sliderContainer,
				'<li><div class="thumb_image"><img src="'
						+ this.imageServerUrl
						+ this.imageUrl +'?img_folder=small&image_id={id}" alt="Image" width="70" height="70" /><span class="{rec_class_name}" ></span></div></li>',
				{
					singleSelect : true,
					store : this.store
				});
		
		

		this.slider.on('click', function(v, index, node, e) {
			this.cursor = index;
			this.onClick('');
		}, this);

		/* Updates main menu delete/undelete item */
		this.menuContainer = Ext.get('menu_content');
		if (this.menuContainer && this.albumPaid!=1) {
			this.menuContainer.clean();
			this.undeleteLink = Ext.DomHelper.insertFirst(this.menuContainer, {
				tag : 'li',
				cls : 'delete undelete',
				children : [{
					tag : 'a',
					href : '#',
					html : 'Un-delete image',
					cls:'png'
				}]
			}, true);
			this.deleteLink = Ext.DomHelper.insertFirst(this.menuContainer, {
				tag : 'li',
				cls : 'delete',
				children : [{
					tag : 'a',
					href : '#',
					html : 'Delete image'
				}]
			}, true);
			this.undeleteLink.setVisibilityMode(Ext.Element.DISPLAY).hide()
					.child('a').on('click', this.discard.bind(this, false));
			this.deleteLink.setVisibilityMode(Ext.Element.DISPLAY).hide()
					.child('a').on('click', this.discard.bind(this, true));
		}

		this.titleElement = Ext.get(document.body)
				.child('.bg-menu span[name=title]');

		this.store.on('load', this.onLoad, this);
		this.store.load({
			params : {
				page : this.page,
				pageSize : this.pageSize
			}
		});
	},
	onClick : function(buttonId) {
		if (this.buttons[buttonId]
				&& this.buttons[buttonId].hasClass('disabled')) {
			return false;
		}
		var params = {
			page : this.page,
			pageSize : this.pageSize
		};
		var oldPage = this.page;
		switch (buttonId) {
			case 'prev' :
				if (this.cursor > 0) {
					params.image_id = this.store.getAt(--this.cursor);
					break;
				}
			case 'prevPage' :
				if (this.page > 0) {
					this.cursor = (buttonId != 'prev') ? 0 : --this.cursor;
					params.page = --this.page;
					break;
				}
			case 'firstPage' :
				this.cursor = (buttonId != 'prev') ? 0 : --this.cursor;
				params.page = this.page = 0;
				break;
			case 'next' :
				if (this.cursor < this.store.getCount() - 1) {
					params.image_id = this.store.getAt(++this.cursor);
					break;
				}
			case 'nextPage' :
				if (this.page < this.pagesCount - 1) {
					this.cursor = (buttonId != 'next') ? 0 : ++this.cursor;
					params.page = ++this.page;
					break;
				}
			case 'lastPage' :
				this.cursor = (buttonId != 'next')
						? 0
						: ((this.cursor < this.store.getCount() - 1)
								? ++this.cursor
								: this.cursor);
				params.page = this.page = this.pagesCount - 1;
				break;
		}
		if (oldPage != params.page) {
			this.store.load({
				params : params
			});
		} else {
			this.onLoad(this.store, null, {
				params : params
			});
		}
	},
	onLoad : function(ds, r, o) {
		this.page = o.params ? o.params.page : 0;
		this.cursor = ((this.cursor || 0) + this.pageSize) % this.pageSize;
		this.imagesCount = ds.getTotalCount();
		this.sliderContainer.setWidth(Ext.get(this.slider.getNode(0)).getWidth()*ds.getCount());
		
		this.pagesCount = Math.ceil(this.imagesCount / this.pageSize);
		this.sliderCaption.update(this.captionTpl.applyTemplate({
			img : this.page * this.pageSize + this.cursor + 1,
			imgCount : this.imagesCount
		}));
		this.__setDisabled('prev', (this.cursor == 0 && this.page <= 0));
		this.__setDisabled('prevPage', (this.page <= 0));
		this.__setDisabled('firstPage', (this.page <= 0));
		this
				.__setDisabled(
						'next',
						(this.cursor >= (this.store.getCount() - 1) && this.page >= this.pagesCount
								- 1));
		this.__setDisabled('nextPage', (this.page >= this.pagesCount - 1));
		this.__setDisabled('lastPage', (this.page >= this.pagesCount - 1));
		this.displayImage();
	},
	displayImage : function() {
		this.cursor = ((this.cursor || 0) + this.pageSize) % this.pageSize;
		var image_id = this.store.getAt(this.cursor).data.id;
            var imageOptions1 = this.store.getAt(this.cursor).data;
             if(imageOptions1.is_cover==true){
                document.getElementById("coverchk").innerHTML="Album Cover Yes";
              }else{
               document.getElementById("coverchk").innerHTML="Album Cover No";
             }
                
                      document.getElementById("defective").innerHTML=imageOptions1.is_defect;
                

       	var imageContainer = Ext.get(this.imageContainer).update('');
		var image = new Ext.Element(document.createElement('img')).set({
			cls : 'big',
			src : this.imageServerUrl + this.imageUrl + '?image_id=' + image_id + '&'
					+ Math.random()
		});

		var onImageLoadCallback = function(ct, newImg) {
			var imageOptions = this.store.getAt(this.cursor).data;
			/* Clear top adds container */
			var tC = (Ext.get('idc-menu-body'))?Ext.get('idc-menu-body').child('.small_page'):null;
			if (tC && tC.remove) {
				tC.remove();
			}
			var iconsContainer = Ext.DomHelper.insertFirst(ct, {
				tag : 'div',
				cls : 'oh',
				id : 'main-image-icons-container',
				style : {
					position : 'absolute',
					width : '500px'
				}
			}, true);
			
			//adding message for restored images
			/*
			var tR = (Ext.get('idc-restoredmessage-area'))?Ext.get('idc-restoredmessage-area').child('span'):null;
			if (tR&& tR.remove) {
				tR.remove();
			}
			
			if (imageOptions.reconstructed_id <= 0 && imageOptions.deleted) {
				var restoreddiscarder="In addition to our manual FREE standard image processing, we have identified a few scans worthwhile of our Advanced Restoration service. To illustrate the benefit of this service we have already performed the restoration. If you do not wish to retain the restored version of the photo and pay the corresponding restoration charge (based on the time spend by our restoration artist), simply click on the NO button to reject the Restored photo.";
				var tRPanel = {
					tag : 'span',
					html : '<p>'+restoreddiscarder+'</p>'
				};
				tRD = Ext.DomHelper.insertFirst(Ext.get('idc-restoredmessage-area'),tRPanel, true);
				
			}
			
			if (imageOptions.reconstructed_id <= 0 && !imageOptions.deleted) {
				
				var tRPanel = {
					tag : 'span',
					html : '<p>You have currently chosen to reject this Restored photo.  You can click the YES button to purchase the restored photo.</p>'
				};
				tRI = Ext.DomHelper.insertFirst(Ext.get('idc-restoredmessage-area'),
						tRPanel, true);
				
			}
			*/
			
			
			
			if (imageOptions.reconstructed_id > 0 && imageOptions.is_paid<1) {
				/* Show first panel */
			var tCPanel = {
					tag : 'div',
					cls : 'small_page',
					html : '<div class="restore_menu_1"><br /><b>Attention!</b><br /> Our technicians have manually <strong>Restored</strong> this original. Click on the button to see the result.</div><div class="bottom"><a href="#" class="oh"><img class="png" src="'
							+ this.shareImagesUrl
							+ 'new_image/b_continue_restored1.png" alt="Show reconstructed options" width="148" height="34" align="middle" border="0"/></a></div>'
				};
				tC = Ext.DomHelper.insertFirst(Ext.get('idc-menu-body'),
						tCPanel, true);
				var nextButton = tC.child('a');
				if (nextButton && nextButton.on) {
                    
					nextButton.on('click', this.__proceedReconstructed, this);
				}
			}
			
			dF = (Ext.get('defective'))?Ext.get('defective').update(imageOptions.is_defect):null;
				
			var image = ct.child('img.big');
			ct.unmask(true);
			if (image) {
				newImg.replace(image);
			} else {
				ct.appendChild(newImg);
			}
			ct.setSize(newImg.getSize(), true, false)/*.center(newImg)*/;
         // alert(imageOptions.is_reconstructed);
			        
			if (imageOptions.is_reconstructed > 0 ) {
             
				//imageOptions.reconstructed_price = this.store.getById(imageOptions.original_id).data.reconstructed_price;
					if (imageOptions.reconstructed_id <= 0 && imageOptions.deleted) {
				/* Show first panel */
				var restoreddiscarder="You have currently chosen to reject this <strong>\"Restored\"</strong> photo.  You can select the <font color=\"#ACD946\"><strong>YES</strong></font> option and click the \"Continue\" button to purchase the <strong>restored</strong> photo."
				}else if(imageOptions.reconstructed_id <= 0 && !imageOptions.deleted){
					//var restoreddiscarder="In addition to our manual FREE standard image processing, we have identified a few scans worthwhile of our <strong><I>Advanced Restoration</I></strong> service. To illustrate the benefit of this service we have already performed the restoration. If you do not wish to retain the restored version of the photo and pay the corresponding restoration charge (based on the time spend by our restoration artist), simply select the <font color=\"#ff0000\">NO</font> option and click \"Continue\" button to reject the <strong>\"Restored\"</strong> photo.";
					var restoreddiscarder = "You have currently chosen to retain this <strong>\"Restored\"</strong> photo.  You can select the <font color=\"#FF0000\"><strong>NO</strong></font> option and click the \"Continue\" button to reject the <strong>restored</strong> photo."
					}
				var reconstructedIcon = Ext.DomHelper.append(iconsContainer.setSize(
							newImg.getSize(), true, false), {
						tag : 'span',
						name : 'reconstructed',
						cls : 'reconstructed-icon fr' + ((!imageOptions.deleted && imageOptions.included)?' included':'')
					});
				var menuBody = Ext.get('idc-menu-body')
				if (menuBody && imageOptions.is_paid<1) {
					var tC = Ext.get('idc-menu-body').child('.small_page');
					if (tC && tC.remove) {
						tC.remove();
					}
					var tCPanel = {
						tag : 'div',
						cls : 'small_page',
						html : '<p class="restore_menu_2"><img class="png fl" hspace="5" src="'
							+ this.shareImagesUrl
							+ 'new_image/i_r_y_green.png" alt="advanced" align="middle" border="0"/>This restored image has been added to your cart at the special rate of $'
							+ imageOptions.reconstructed_price
							+ '.</p><div class="bottom">'
							+ '<div align="center" style="text-align:center;">'
							+ '<div  style="float:left; margin-left:30px;"><label for="yes_radio">YES<br><span>ACCEPT</label><br><input type="radio" name="radiobutton" id="yes_radio" checked="checked"></span></div>'
							+ '<div><label for="no_radio" class="red">NO<br><span>REMOVE</label><br><input type="radio" name="radiobutton" id="no_radio"></span></div>'
							+ '</div>'
							+ '<div><a href="javascript:void(0);" class="no"><img class="png" src="'
							+ this.shareImagesUrl
							+ 'new_image/b_view_original_restored.png" alt="advanced" width="106" height="30" align="middle" border="0"/></a><a href="javascript:void(0);" class="yes"><img class="png" src="'
							+ this.shareImagesUrl
							+ 'new_image/b_continue_restored2.png" alt="advanced" width="107" height="30" align="middle" border="0"/></a></div></div><div style="border:3px solid #FF6600;text-align:justify;font-size:15px">'+restoreddiscarder+'</div>'
					}
					
					tC = Ext.DomHelper.insertFirst(menuBody,tCPanel, true);
					if (tC) {
						var back = tC.child('a.no');
						var process = tC.child('a.yes');
						back.on('click', this.__proceedReconstructed, this);
						
						var params = {
							image_id : imageOptions.id
						};
						process.on('click', function() {
							var yes_radio = Ext.get("yes_radio");
							var saveReconstructed = (yes_radio && yes_radio.dom)
								? yes_radio.dom.checked
								: false;
							params.act = (saveReconstructed)
								? 'reconstructed_add'
								: 'reconstructed_remove';
							var success = function() {
								this.store.load({
									params : {
										page : this.page,
										pageSize : this.pageSize
									}
								});
							}.bind(this);
							this.store.getAt(this.cursor).data.reconstructed_id = 0;
							this.__request({
								params : params,
								success : success
							});
						}.bind(this));
					}
				}
			}

			/* Adding icons for deleted images */
			if (this.undeleteLink || this.deleteLink) {
				this[(imageOptions.deleted) ? "undeleteLink" : "deleteLink"].show();
				this[(!imageOptions.deleted) ? "undeleteLink" : "deleteLink"].hide();
				if (imageOptions.deleted) {
					var deletedIcon = Ext.DomHelper.append(iconsContainer.setSize(
							newImg.getSize(), true, false), {
						tag : 'span',
						name : 'deleted',
						cls : 'deleted-icon fr'
					});
					ct.mask();
				}
				
			}

			if (this.titleElement) {
				this.titleElement.update(imageOptions.filename);
			}
			this.onImageLoad();
		};
	image.on('load', onImageLoadCallback.bind(this, imageContainer, image));
	},
	discard : function(isDiscard) {
		var params = {
			act : (isDiscard) ? 'delete' : 'undelete',
			image_id : this.store.getAt(this.cursor).data.id
		};
		var success = function(rq, options) {
			var isDeleted = this.store.getAt(this.cursor).data.deleted = (options.params.act == 'delete');
			this.store.load({
				params : {
					page : this.page,
					pageSize : this.pageSize
				}
			});
		}.bind(this);
		this.__request({
			params : params,
			success : success
		});
		return false;
	},
	rotate : function(angle) {
		var params = {
			act : 'rotate',
			image_id : this.store.getAt(this.cursor).data.id,
			angle : angle
		};
		this.__request({
			params : params,
			success : this.__refreshImage.bind(this)
		});
		return false;
	},
	flip : function() {
		var params = {
			act : 'flip',
			image_id : this.store.getAt(this.cursor).data.id
		};
		this.__request({
			params : params,
			success : this.__refreshImage.bind(this)
		});
		return false;
	},
	__refreshImage : function() {
		var store = new Ext.data.Store({});
		var oldId = this.slider.store.getAt(this.cursor).data.id;
		this.slider.store.getAt(this.cursor).data.id += '&' + Math.random(); 
		this.slider.refreshNode(this.cursor);
		this.slider.store.getAt(this.cursor).data.id = oldId;
		this.displayImage();
	},
	__setDisabled : function(button, disabled) {
		if (this.buttons[button]) {
			if (disabled) {
				this.buttons[button].addClass('disabled');
			} else {
				this.buttons[button].removeClass('disabled');
			}
		}
	},
	__request : function(options) {
		var params = options.params || {};
		var success = options.success || this.displayImage.bind(this);
		Ext.Ajax.request({
			url : this.baseUrl + 'image.delete.request.php',
			params : params,
			method : 'POST',
			success : success
		});
	},
	__proceedReconstructed : function() {
		var imageOptions = this.store.getAt(this.cursor).data;
		this.__originalId = imageOptions.id;
		this.__reconstructedId = imageOptions.reconstructed_id
            
		this.cursor = imageOptions.position;
		this.page = Math.floor(this.cursor / this.pageSize);
		this.cursor = this.cursor % this.pageSize;
        this.store.load({
			params : {
				page : this.page,
				pageSize : this.pageSize
			}
		});
      // this.__refreshImage.bind(this);
      
		
	},
	__acceptReconstructed : function() {

	},
	__declineReconstructed : function() {

	}
}