GuideManager = Class.create();

GuideManager.prototype = Object.extend(new ajax(), {

	getCountryInfo: function(id,ele) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=edit&cID='+id+'&field='+ele;
		this.update   = $('INPUTAREA');
		this.request('countryInfo.php');
		this.onComplete = this.hideLoading;
	},
	
	saveCountryInfo: function(){
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=update&cID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&value='+encodeURIComponent($F('txtContent'));
		this.update   = $($F('hidElement'));
		this.request('countryInfo.php');
		this.onComplete = this.closePopup;
	},
	
	getCountryCode: function(id,ele) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editCountryCode&cID='+id+'&element='+ele;
		this.update   = $('INPUTAREA');
		this.request('country.php');
		this.onComplete = this.hideLoading;
	},
	
	saveCountryCode: function() {
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=updateCountryCode&cID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&value='+encodeURIComponent($F('txtContent'));
		this.update   = $($F('hidElement'));
		this.request('country.php');
		this.onComplete = this.closePopup;
	},
	
	getCityCode: function(id,ele) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editCityCode&ctID='+id+'&element='+ele;
		this.update   = $('INPUTAREA');
		this.request('city.php');
		this.onComplete = this.hideLoading;
	},
	
	saveCityCode: function() {
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=updateCityCode&ctID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&value='+encodeURIComponent($F('txtContent'));
		this.update   = $($F('hidElement'));
		this.request('city.php');
		this.onComplete = this.closePopup;
	},
	
	getTeaserDescription: function(id,ele) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editDescription&gID='+id+'&element='+ele;
		this.update   = $('INPUTAREA');
		this.request('guide.php');
		this.onComplete = this.hideLoading;
	},
	
	saveTeaserDescription: function() {
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=updateDescription&gID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&description='+encodeURIComponent($F('txtContent'));
		this.update   = $($F('hidElement'));
		this.request('guide.php');
		this.onComplete = this.closePopup;
	},
	
	getTeaserTitle: function(id,ele) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editTitle&gID='+id+'&element='+ele;
		this.update   = $('INPUTAREA');
		this.request('guide.php');
		this.onComplete = this.hideLoading;
	},
	
	saveTeaserTitle: function() {
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=updateTitle&gID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&title='+encodeURIComponent($F('txtContent'));
		this.update   = $($F('hidElement'));
		this.request('guide.php');
		this.onComplete = this.closePopup;
	},
	
	getGuideArticle: function(id,ele,country){
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editGuideArticle&gID='+id+'&element='+ele,'&country='+country;
		this.update   = $('INPUTAREA');
		this.request('guide.php');
		this.onComplete = this.hideLoading;
	},
	
	saveGuideArticle: function() {
		var param = 'mode=updateGuideArticle&gID='+$F('hidPrimaryID')+'&field='+$F('hidElement')+'&title='+encodeURIComponent($F('txtTeaserTitle'))+'&description='+encodeURIComponent($F('txtTeaserDescription'))+'&thumbnail='+$F('txtThumbnail')+'&link='+encodeURIComponent($F('hidLink'));
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = param;
		this.update   = $($F('hidElement'));
		this.request('guide.php');
		this.onComplete = this.closePopup;
	},
	
	getTravelToCountry: function(id,ele,cID) {
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editTravel&tID='+id+'&element='+ele+'&cID='+cID;
		this.update   = $('INPUTAREA');
		this.request('travel.php');
		this.onComplete = this.hideLoading;
	},
	
	saveTravelToCountry: function() {
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = 'mode=updateTravel&tID='+$F('hidPrimaryID')+'&title='+encodeURIComponent($F('txtTitle'))+'&description='+encodeURIComponent($F('txtDescription'));
		this.update   = $($F('hidElement'));
		this.request('travel.php');
		this.onComplete = this.closePopup;
	},
	
	addTravelToCountry: function(id, ele) {
		var param = 'mode=addTravel&cID='+id+'&element='+ele+'&tID=0';
		this.openPopup('Loading...');
		this.init();
		this.postBody = param;
		this.update   = $('INPUTAREA');
		this.request('travel.php');
		this.onComplete = this.hideLoading;
	},
	
	getFullArticle: function(id,cID){
		this.openPopup('Loading...');
		this.init();
		this.postBody = 'mode=editFullArticle&gID='+id+'&cID='+cID;
		this.update   = $('INPUTAREA');
		this.request('guide.php');
		this.onComplete = this.hideLoading;
	},
	
	saveFullArticle: function(){
		//alert(escape($F('txtDescription')));return;
		var param = 'mode=updateFullArticle&gID='+$F('hidPrimaryID')+'&cID='+$F('hidCountryID')+'&title='+encodeURIComponent($F('txtTitle'))+'&description='+encodeURIComponent($F('txtDescription'))+'&thumbnail='+$F('txtThumbnail')+'&sources='+$F('txtSource')+'&contributor='+$F('txtContributor');
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = param;
		this.update   = $('page_intro_article');
		this.request('guide.php');
		this.onComplete = this.closePopup;
	},

	getChangeCountry: function(gID,cID){
		var param = 'mode=editCountrySelection&gID='+gID+'&cID='+cID;
		this.openPopup('Loading...');
		this.init();
		this.postBody = param;
		this.update   = $('INPUTAREA');
		this.request('country.php');
		this.afterUpdate = this._mRegisterDragAndDrop;
	},
	
	saveSelectedCountry: function(){
		var countryList     = $A($('selectedCountry').getElementsByTagName('li'));
		var arrCountry      = new Array();
		var reLocate        = true;
		var default_country = '';
		countryList.each(function(country){
			default_country = country.getAttribute('id');
			arrCountry.push(country.getAttribute('id')); 
			if( country.getAttribute('id')==$F('hidCountry') ) reLocate = false;
		});
		arrCountry.join(',');
		var param = 'mode=updateCountrySelection&gID='+$F('hidGuideID')+'&countryList='+arrCountry+'&country='+$F('hidCountry');
		this.showInitLoading('Saving...');
		this.init();
		this.postBody = param;
		this.request('country.php');
		
		if ( reLocate ){
			//this._redirect($F('hidGuideID'), default_country+'.html');
			this._gID     = $F('hidGuideID');
			this._country = default_country+'.html';
		}else{	
			this.update     = $('body');
			this.onComplete = this.closePopup; 
		}
	},
		
	getChangeCategory: function(gID,catID){
		var param = 'mode=editCategory&gID='+gID+'&catID='+catID;
		this.openPopup('Loading...');
		this.init();
		this.postBody = param;
		this.update   = $('INPUTAREA');
		this.request('category.php');
		this.onComplete = this.hideLoading;
	},
	
	saveCategoryandSubcategory: function(){
		var arrCatID    = new Array();
		var arrSubCatID = new Array();
		var reLocate    = true;
		var proceed     = false;
		var param;
		for (var i = 0; i < document.sform.elements.length; i++) {
			if(document.sform.elements[i].type == 'checkbox' && document.sform.elements[i].checked){
				arrCatID.push(document.sform.elements[i].value);
				proceed = true;
				if( $F('hidCatID') == document.sform.elements[i].value ) reLocate = false;
			}
		}

		if( proceed ){
			$A($('selectedSubcategoryList')).each(function( subCatID ){
				arrSubCatID.push(subCatID.value);
			});
			arrCatID.join(',');
			arrSubCatID.join(',');
			param = 'mode=updateCategory&categoryIDList='+arrCatID+'&subCategoryIDList='+arrSubCatID+'&gID='+$F('hidGuideID')+'&catID='+$F('hidCatID');
			this.showInitLoading('Saving...');
			this.init();
			this.postBody = param;
			this.request('category.php');
			this.update     = $('body');
			this.onComplete = this.closePopup; 
			if( reLocate ){
				pos     = location.pathname.lastIndexOf('/');
				country = location.pathname.substring(pos+1,location.pathname.length);
				//this._redirect($F('hidGuideID'), country);
				this._gID     = $F('hidGuideID');
				this._country = country;
				this.onComplete = this._relocate;
			}else
				this.onComplete = this.closePopup;
		}else{
			alert('Unable to save changes! You must at least choose 1 category.');
		}
	},
	
	deleteGuide: function(gID, country, cID){
		var proceed  = confirm('Are you sure you want to delete this guide?');
		if( proceed ){
			var param = 'mode=deleteGuide&gID='+gID+'&cID='+cID;
			this.country = country;
			this.init();
			this.postBody = param;
			this.request('guide.php');
			this.update     = $('body');
			this.onComplete = this._refresh; 
		}
	},
	
	_refresh: function(){
		this._redirect(0, this.country);
	},
	
	_relocate: function(){
		var gID     = this._gID;
		var country = this._country;
		this._redirect(gID, country);
	},
	
	_redirect: function(gID, country){
		var hostname = location.hostname;
		if( gID ){
			if( hostname.substring(0,3) == 'www' || hostname.substring(0,3) == 'dev' )
				window.location.href = 'http://'+hostname+'/admin/newGuides/'+country+'?gID='+gID;
			else
				window.location.href = 'http://'+hostname+'/'+country+'?gID='+gID;
		}else{
			if( hostname.substring(0,3) == 'www' || hostname.substring(0,3) == 'dev' )
				window.location.href = 'http://'+hostname+'/admin/newGuides/'+country+'.html';
			else
				window.location.href = 'http://'+hostname+'/'+country+'.html';
		}
	},
	
	openPopup: function(msg){
		$('theLayer_content').style.display = "block";
		this.closePopup();
		this.showLoading(msg);
		//Effect.Appear($('theLayer'));
		$('theLayer').show();
		this._center();
	},
	
	closePopup: function(){
		this.hideLoading();
		$('theLayer').hide();
		//Effect.Fade($('theLayer'));
	},

	showInitLoading: function() {
		$('theLayer_content').style.display = "none";
		this.showLoading('Saving...');
	},
	
	showLoading: function(msg) {
		$('MESSAGE').innerHTML = msg;
		$('status_bar').style.display = "block";
	},
	
	hideLoading: function() {
		$('status_bar').style.display = "none";
		$('MESSAGE').innerHTML   = '';
		$('INPUTAREA').innerHTML = '';
	},
	
	preview: function(ele) {
		$('IMAGE-PREVIEW').src = $F('hidPath')+$F(ele);
	},
	
	populateSubcategory: function(catID){
		$('subcategoryList').options.length = 0;
		$('ERRORMSG').style.display = 'none';
		var newopt;
		var catID;
		for (var i = 0; i < document.sform.elements.length; i++) {
			if(document.sform.elements[i].type == 'checkbox' && document.sform.elements[i].checked){
				catID = document.sform.elements[i].value;
				selectedList = $A($('cboSubCategory').getElementsByTagName('option'));
				selectedList.each(function(list){
					pos = list.value.indexOf('-');
					categoryID    = list.value.substring(0,pos);
					subcategoryID = list.value.substring(pos+1,list.value.length);
					if( categoryID == catID ){
						newopt       = new Option;
						newopt.text  = list.innerHTML;
				        newopt.value = subcategoryID;
		        		$('subcategoryList').appendChild(newopt);
		        	}
				});
			}
		}

		for( var j = ($('selectedSubcategoryList').options.length-1); j >= 0; j--){
			selectedCategoryID = $('selectedSubcategoryList').options[j].value;
			IsIntheList = false;
			for( var k = 0; k < $('subcategoryList').options.length; k++){
				pos = $('subcategoryList').options[k].value.indexOf('-');
				subcategoryID = $('subcategoryList').options[k].value.substring(pos+1,$('subcategoryList').options[k].value.length);
				if( subcategoryID == selectedCategoryID ){
					IsIntheList = true;
					break;
				}
			}
			if( !IsIntheList ) $('selectedSubcategoryList').remove(j);
		}
		if( $('subcategoryList').options.length==0 ) $('selectedSubcategoryList').options.length = 0;
	},
	
	populateSelectedCategory: function(){
		$('ERRORMSG').style.display = 'none';
		var pos    = document.getElementById('subcategoryList').selectedIndex;
		var text  = document.getElementById('subcategoryList').options[pos].text;
		if( !this._isSelected(text) ){
			var newopt = new Option;
			newopt.text  = text;
	        newopt.value = $('subcategoryList').value;
	        $('selectedSubcategoryList').appendChild(newopt);
        }else{
        	$('ERRORMSG').style.display = 'block';
        }	
   	},
	
	removeSelectedCategory: function(){
		if( $('selectedSubcategoryList').options.length ){
			var pos = $('selectedSubcategoryList').selectedIndex;
			$('selectedSubcategoryList').remove(pos);
		}
	},
	
	_isSelected: function(text){
		var isSelected = false;
		for( var j = ($('selectedSubcategoryList').options.length-1); j >= 0; j--){
			if( $('selectedSubcategoryList').options[j].text == text ){
				isSelected = true;
				break;
			}
		}
		return isSelected;
	},
	
	_mRegisterDragAndDrop: function(){
		$('status_bar').style.display = "none";
		$('MESSAGE').innerHTML   = '';
		Sortable.create("countryList",{dropOnEmpty:true,containment:["countryList","selectedCountry"],ghosting:true,onUpdate:this._mSort});
 	  	Sortable.create("selectedCountry",{dropOnEmpty:true,containment:["countryList","selectedCountry"],ghosting:true,onUpdate:this._mSort});
	},
	
	_mSort: function(){
		
		if ( $('selectedCountry').getElementsByTagName('li').length > 1)
			$('lblCountry').innerHTML = 'Selected Countries';
		else
			$('lblCountry').innerHTML = 'Selected Country';
		
		/*var countryList = $('selectedCountry').getElementsByTagName('li');
		var myLists     = new Array();
		var countries   = $A(countryList);
		var tag;

		for( i=0; i<countries.length; i++ ){
			for( j=0; j<countries.length-1; j++ ){
				str1 = countries[j].innerHTML;
				str2 = countries[j+1].innerHTML;
				if( str1 > str2 ){
					temp           = countries[j+1];
					countries[j+1] = countries[j];
					countries[j]   = temp;
					elem1          = $(temp.getAttribute('id'));
					elem2          = $(countries[j+1].getAttribute('id'));
					alert(elem1.parentNode.innerHTML);
					elem1.parentNode.insertBefore(elem1,elem1);
					//$('selectedCountry').parentNode.insertBefore(countries[j+1].innerHTML,countries[j+1].innerHTML);
					//alert(temp.innerHTML + ' = ' +countries[j+1].innerHTML);
				}
			}
		}
		countries.each(function(country){
			myLists.push(country.innerHTML);
		});
		myLists.sort();
		$('selectedCountry').innerHTML = '';
		for(i=0; i<=(myLists.length-1); i++){
			tag = document.createElement('li');
			tag.setAttribute('itemID', myLists[i]);
			tag.style.cursor = "move";
		    tag.style.padding = "1px 1px";
		    tag.style.marginBottom = "2px";
		    tag.style.backgroundColor = "#eee";
		    tag.style.border = "1px solid #ccc";
		    tag.innerHTML = myLists[i];
		    tag.style.position = "relative";
		    $('selectedCountry').appendChild(tag);
		}*/
	},
	
	_compare: function(a,b){
		return a < b ? -1 : a == b ? 0 : 1;
	},
	
	_center: function() {
		var windowScroll = this._getWindowScroll();    
		var pageSize = this.getPageSize();    
		var top = 150;
		var left = 150;
		
	    if (!top)
	      top = (pageSize.windowHeight - (this.height + this.heightN + this.heightS))/2;
	    top += windowScroll.top
	    
	    if (!left)
	      left = (pageSize.windowWidth - (this.width + this.widthW + this.widthE))/2;
	    left += windowScroll.left 
	    
	    if( $('theLayer').style.width == "700px"){
	    	left = left+20;
	    	top = top-50;
		}else
		    left = left+110;
	    $('theLayer').style.top  = top + 'px';
	    $('theLayer').style.left = left + 'px';
	
	},

	_getWindowScroll: function() {
		var w = window;
		var T, L, W, H;
		with (w.document) {
			if (w.document.documentElement && documentElement.scrollTop) {
		  		T = documentElement.scrollTop;
			  	L = documentElement.scrollLeft;
			} else if (w.document.body) {
			  	T = body.scrollTop;
		  		L = body.scrollLeft;
			}
			if (w.innerWidth) {
			  	W = w.innerWidth;
		  		H = w.innerHeight;
			} else if (w.document.documentElement && documentElement.clientWidth) {
			  	W = documentElement.clientWidth;
			  	H = documentElement.clientHeight;
			} else {
		      	W = body.offsetWidth;
		     	H = body.offsetHeight
		    }
		}
	 	return { top: T, left: L, width: W, height: H };
	 },
	 
	 getPageSize: function(){
	  	var xScroll, yScroll;
	
	  	if (window.innerHeight && window.scrollMaxY) {	
	  		xScroll = document.body.scrollWidth;
	  		yScroll = window.innerHeight + window.scrollMaxY;
	  	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	  		xScroll = document.body.scrollWidth;
	  		yScroll = document.body.scrollHeight;
	  	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	  		xScroll = document.body.offsetWidth;
	  		yScroll = document.body.offsetHeight;
	  	}
	
	  	var windowWidth, windowHeight;
	
	  	if (self.innerHeight) {	// all except Explorer
	  		windowWidth = self.innerWidth;
	  		windowHeight = self.innerHeight;
	  	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	  		windowWidth = document.documentElement.clientWidth;
	  		windowHeight = document.documentElement.clientHeight;
	  	} else if (document.body) { // other Explorers
	  		windowWidth = document.body.clientWidth;
	  		windowHeight = document.body.clientHeight;
	  	}	
	  	var pageHeight, pageWidth;
	
	  	// for small pages with total height less then height of the viewport
	  	if(yScroll < windowHeight){
	  		pageHeight = windowHeight;
	  	} else { 
	  		pageHeight = yScroll;
	  	}
	
	  	// for small pages with total width less then width of the viewport
	  	if(xScroll < windowWidth){	
	  		pageWidth = windowWidth;
	  	} else {
	  		pageWidth = xScroll;
	  	}
	
	  	return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
	}
	 
} );