/*
* WebShopUtil
* 
* @brief: misc utilities for webshop
*/
function WebShopUtil() {
	this.browserType = '';
	this.browserVer = '';
	this.aktivcsillag = 0;
	this.szallitasicim = 0;
	this.atvetelitipus = '';
	this.szamlazasicim = 0;

	this.prevSelectedEventCellId = '';
	this.prevSelectedEventCellClass = '';
	this.actualSelectedTimeCellId = '';

	this.actualSelectedLocationId = 0;
	this.actualWeek = 0;
	this.actualYear = 0;
	this.eventProdId = 0;

	this.setBrowser();
}

/*
* WebShopUtil.getBrowser
* 
* @brief: get browser datas
* @args:	neededData:String (optional) - type/version/platform/short for browsername/browser version/opsys/brief desc like ie7, ff2
* @return:	strig with required data or null
*
*/
WebShopUtil.prototype.getBrowser = function( neededData ) {
	switch( neededData ) {
		case 'type':
			return this.browserType;
			break;
		case 'version':
			return this.browserVer;
			break;
		case 'short':
			return this.browserType + this.browserVer;
			break;
		default:
			return null;
	}
}

/*
* WebShopUtil.setBrowser
* 
* @brief: set browser datas
* @args:	-
* @return:	-
*
*/
WebShopUtil.prototype.setBrowser = function() {
	var agentInfo = navigator.userAgent.toLowerCase();

	if( agentInfo.indexOf( "msie" ) > -1 ) {	// ie
		this.browserType = 'ie';
		this.browserVer = parseFloat( agentInfo.substring( agentInfo.indexOf( 'msie' ) + 'msie'.length + 1 ) );
	} else if( agentInfo.indexOf( "firefox" ) > -1 ) {	// ff
		this.browserType = 'ff';
		this.browserVer = parseFloat( agentInfo.substring( agentInfo.indexOf( 'firefox' ) + 'firefox'.length + 1 ) );
	} else if( agentInfo.indexOf( "chrome" ) > -1 ) {	// chrome
		this.browserType = 'chrome';
		this.browserVer = parseFloat( agentInfo.substring( agentInfo.indexOf( 'chrome' ) + 'chrome'.length + 1 ) );
	} else if( agentInfo.indexOf( "safari" ) > -1 ) {	// safari
		this.browserType = 'safari';
		this.browserVer = parseFloat( agentInfo.substring( agentInfo.indexOf( 'version' ) + 'version'.length + 1 ) );
	} else if( agentInfo.indexOf( "opera" ) > -1 ) {	// opera
		this.browserType = 'opera';
		this.browserVer = parseFloat( agentInfo.substring( agentInfo.indexOf( 'opera' ) + 'opera'.length + 1 ) );
	}
}

/*
* WebShopUtil.changeCSSStyle
* 
* @brief: change given obj's given style param
* @args:	dom:obj - obj of dom
*			cssStyleTag:String - name of the css tag in javascript
*			cssStyleValue:String - new value
* @return:	-
*
*/
WebShopUtil.prototype.changeCSSStyle = function( dom , cssStyleTag , cssStyleValue ) {
	if( typeof( dom ) == 'string' ) {
		eval( "get( '" + dom + "' ).style." + cssStyleTag + " = '" + cssStyleValue + "';" );
	} else if( typeof( dom ) == 'object' ) {
		eval( "dom.style." + cssStyleTag + " = '" + cssStyleValue + "';" );
	}
}

/*
* WebShopUtil.changeCSSClass
* 
* @brief: change given obj's class to given class
* @args:	dom:obj - obj of dom
*			className:String - name of the css class
* @return:	-
*
*/
WebShopUtil.prototype.changeCSSClass = function( dom , className ) {
	if( typeof( dom ) == 'string' ) {
		eval( "get( '" + dom + "' ).className = '" + className + "';" );
	} else if( typeof( dom ) == 'object' ) {
		eval( "dom.className = '" + className + "';" );
	}
}
/*
* WebShopUtil.toTop
* 
* @brief: scroll to top
* @args:	-
* @return:	-
*
*/
WebShopUtil.prototype.toTop = function() {
	self.scrollTo( 0 , 0 );
}

/*
* WebShopUtil.capitalize
* 
* @brief: capitalize given str
* @args:	inStr:String - str to capitalize
* @return:	String with theresult
*
*/
WebShopUtil.prototype.capitalize = function( inStr ) {
	return inStr.replace(/\w+/g, function( inStr ) {
		return inStr.charAt( 0 ).toUpperCase() + inStr.substr( 1 ).toLowerCase();
	} );
};

/*
* WebShopUtil.ltrim
* 
* @brief: trim left whitespaces
* @args:	str:String - str to left trim
* @return:	String with the result
*
*/
WebShopUtil.prototype.ltrim = function( str ) {
	return str.replace( new RegExp( "^[\\s]+" , "g" ) , "" );
}

/*
* WebShopUtil.rtrim
* 
* @brief: trim right whitespaces
* @args:	str:String - str to right trim
* @return:	String with the result
*
*/
WebShopUtil.prototype.rtrim = function( str ) {
	return str.replace( new RegExp( "[\\s]+$" , "g" ) , "" );
}

/*
* WebShopUtil.trim
* 
* @brief: trim whitespaces
* @args:	str:String - str to trim
* @return:	String with the result
*
*/
WebShopUtil.prototype.trim = function( str ) {
	return this.ltrim( this.rtrim( str ) );
}

/*
* WebShopUtil.preload
* 
* @brief: show preloader
* @args:	ojjektum:String - dom's name to change content
*			felsomargo:String - margin-top value
* @return:	-
*
*/
ajax.show_preload = WebShopUtil.prototype.preload = function( ojjektum , felsomargo ) {
	if (ojjektum) return // skip old preload calls
	var el = get('modulRight'), p = get('preloader_div')
	if (p) return p.style.display = 'block'
	var style = (core.browser.slice(0, 2) == 'ie' ? 'height: 88px;' : '') + (el ? '' : ' margin-top: 200px;')
	var iemargin = core.browser.slice(0, 2) == 'ie' ? '0' : '210'
	var loadingText = get( "phrase_loading" ) ? get( "phrase_loading" ).value : "Betöltés"
	p = document.createElement('div')
/*	p.innerHTML = '' + 
		"<div id='preloader_div' style='text-align:center; position:absolute; top:0px; left:0px; width:100%; z-index:200;'>" + 
			"<div style='margin:0 auto; z-index:200; width:100px; height:20px; padding-top:5px; background:black; color: white; font-size: 12; font-weight:bold; text-align:center; opacity:0.7; filter:alpha(opacity=70);" + style + "'>" + 
				"<div style='opacity:1.0; filter:alpha(opacity=100);'>" + loadingText + "...</div>" + 
			"</div>" + 
		"</div>"
*/
	p.innerHTML = 
		"<div class='preloader'>" +
			"<div id='preloader_div' style='text-align:center; position:absolute; top:0px; left:0px; width:100%; height: 88px; z-index:2000;'>" + 
				"<div style='margin:0 auto; z-index:200; width:100px; height:88px; padding-top:18px; background:black; color: white; font-size: 12; font-weight:bold; text-align:center; opacity:0.7; filter:alpha(opacity=70);" + style + "'>" + 
					"<div style='opacity:1.0; filter:alpha(opacity=100);'><img src='fw/webshop/rsc/ajax-loader.gif'></div>" + 
				"</div>" + 
			"</div>" + 
		"</div>"
	if (el) el.parentNode.insertBefore(p.firstChild, el)
	else window.document.body.appendChild(p.firstChild)
	return 1
}

ajax.remove_preload = function() {
	//core.debug.debug('removing preloader', 'ajax')
	var el = get('preloader_div')
	if (el) el.style.display = 'none'
}

/*
* WebShopUtil.preload_grey
* 
* @brief: show alternate preloader
* @args:	ojjektum:String - dom's name to change content
*			felsomargo:String - margin-top value
* @return:	-
*
*/
WebShopUtil.prototype.preload_grey = function( ojjektum , felsomargo ) {
	return ws.wsUtil.preload(ojjektum, felsomargo)
}

WebShopUtil.prototype.csillagszinez = function( id ) {
	for( i = 1 ; i <= 5 ; i++ ) {
		nev = 'csillag' + i;
		if( i <= id ) {
			get( nev ).className = 'telecsillaglink';
		} else {
			get( nev ).className = 'urescsillaglink';
		}
	}
}


WebShopUtil.prototype.tovabbaktiv = function( id , tipus , atvetelitipus ) {
	var storetype = '';
	if( typeof( atvetelitipus ) == 'string' ) storetype = atvetelitipus;

	switch( tipus ) {
		case 1:		// szállítási cím
			this.szallitasicim = id;
			this.atvetelitipus = storetype;
			this.setCookie( 'szallitasi' , id , 1 );
			this.setCookie( 'atvetelitipus' , storetype , 1 );
			break;
		case 2:		// számlázási cím
			this.szamlazasicim = id;
			this.setCookie( 'szamlazasi' , id , 1 );
			if( ( get( 'szallitasicimopcio' ) != null ) && ( get( 'szallitasicimopcio' ).value == -3 ) ) {			// létezik és -3, azaz szállítási cím nélküli
				this.szallitasicim = -3;
				this.atvetelitipus = '';			// a value="none", fixen beépítve
				this.setCookie( 'szallitasi' , -3 , 1 );
				this.setCookie( 'atvetelitipus' , '' , 1 );
			}
			break;
		case 3:
//			this.szallitasicim = -1;
			this.szamlazasicim = id;
			this.setCookie( 'szamlazasi' , id , 1 );
			break;
	}
	
	var szallitasicimopcio = document.getElementsByName( 'szallitasicimopcio' );
	var szamlazasicimopcio = document.getElementsByName( 'szamlazasicimopcio' );
	var takeoveraddressoption = document.getElementsByName( 'takeoveraddressoption' );

	var hasAll = 0;
	
	for( var j = 0 ; j < szallitasicimopcio.length ; j++ ) {
		if( szallitasicimopcio[ j ].checked ) {
			hasAll++;
			break;
		}
	}

	for( var j = 0 ; j < szamlazasicimopcio.length ; j++ ) {
		if( szamlazasicimopcio[ j ].checked ) {
			hasAll++;
			break;
		}
	}

	for( var j = 0 ; j < takeoveraddressoption.length ; j++ ) {
		if( takeoveraddressoption[ j ].checked ) {
			hasAll++;
			break;
		}
	}
	
	if( ( this.szallitasicim != 0 ) && ( this.szamlazasicim != 0 ) ) {
		ajax.load( 'public/order/pagesubmitvisible' );
	} else if( hasAll >= 2 ) {
		ajax.load( 'public/order/pagesubmitvisible' );
	} else {
		get( 'cassaaddresssubmit' ).innerHTML = '';
	}
}
		
WebShopUtil.prototype.tovabbaktivreset = function() {
	this.szallitasicim = 0;
	this.szamlazasicim = 0;
}

WebShopUtil.prototype.sortsearchresult = function( change ) {
	var sortclass = get( 'sortarrow' ).className;
	
	if( change ) {
		if( sortclass == 'sort_asc' ) {
			get( 'sortarrow' ).className = 'sort_desc';
		} else {
			get( 'sortarrow' ).className = 'sort_asc';
		}
	}
	return get( 'sortarrow' ).className.substring( 5 );
}

/*
* WebShopUtil.timer
* 
* @brief:	timer function
* @args:	jsCommand:string - javascript command to run
*			secs:int - secumdums to wait
* @return:	-
*
*/
WebShopUtil.prototype.timer = function( jsCommand , secs ) {
	var timer = setTimeout( jsCommand , secs * 1000 );
}

/*
* WebShopUtil.hideMsgDiv
* 
* @brief:	div hider for hide error msgs
* @args:	divId:string - id of the div
*			divDefaultContent:string - default content of the div, which should be restored
* @return:	-
*
*/
WebShopUtil.prototype.hideMsgDiv = function( divId , divDefaultContent ) {
	if( get( divId ) != null ) {	// has this dom
		if( this.trim( get( divId ).innerHTML.toLowerCase() ) != divDefaultContent.toLowerCase() ) {		// not empty
			get( divId ).innerHTML = divDefaultContent;
			if( this.getBrowser( 'type' ) == 'ie' ) {
				get( divId ).style.height = "0px";
			}
		}
	}
}

WebShopUtil.prototype.clearWarnings = function()
{
	if (ws.clearNeeded)
	{
		ws.clearNeeded = false;
		
		if (get( 'newslettererrdiv' )) get( 'newslettererrdiv' ).innerHTML = '';
		if (get( 'newsletterusername' )) ws.wsUtil.changeCSSClass( get( 'newsletterusername' ), '');
		if (get( 'newsletteremail' )) ws.wsUtil.changeCSSClass( get( 'newsletteremail' ), '');
	}
}

WebShopUtil.prototype.setCookie = function( cookieName , cookieValue , expireDays ) {
	var expireDate = new Date();
	if( typeof( expireDays ) == 'number' ) expireDate.setDate( expireDate.getDate() + expireDays );
	else expireDays = null;

	document.cookie = cookieName + "=" + escape( cookieValue ) + ( ( expireDays == null ) ? "" : ";expires=" + expireDate.toUTCString() );
}

WebShopUtil.prototype.deleteCookie = function( cookieName ) {
	var expireDate = new Date();
	document.cookie = cookieName + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

WebShopUtil.prototype.encodeUTF8 = function( s ) {
	if( typeof( s ) == 'undefined' ) return '';
	
	for( var c , i = -1 , l = (s = s.split( '' ) ).length , o = String.fromCharCode ; ++i < l;
		s[ i ] = ( c = s[ i ].charCodeAt( 0 ) ) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[ i ]
	);
	return s.join( '' );
}

WebShopUtil.prototype.decodeUTF8 = function( s ) {
	if( typeof( s ) == 'undefined' ) return '';

	for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
		((a = s[i][c](0)) & 0x80) &&
		(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
		o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
	);
	return s.join( "" );
}

WebShopUtil.prototype.moveDiv = function( divName , styleTag , values ) {
	var elem = get( divName );
	if( elem == null ) return;
	
	var style = null;

	if( elem.currentStyle ) style = elem.currentStyle[ styleTag ];
	else if( window.getComputedStyle ) style = document.defaultView.getComputedStyle( elem , null ).getPropertyValue( styleTag );
	
	if( style == values[ 0 ] ) this.changeCSSStyle( divName , styleTag , values[ 1 ] );
	else this.changeCSSStyle( divName , styleTag , values[ 0 ] );
}
WebShopUtil.prototype.piecesCheck = function(pieces,id) {
	if (id) inputid = id;  
	else inputid = ''; 
	var piecesvalue = parseInt( get( 'mennyiseg' + inputid).value / pieces );
	if( get('mennyiseg' + inputid).value % pieces) {
		get('errordiv' + inputid).style.display='block';
		return false;
	}
	else return true;
}
WebShopUtil.prototype.easyorderCheck = function() {
	var prodId = 0;
	if( get('pieces').value > 0 && ( get( 'prodlist' ).value > 0 || get( 'prodlistarticle' ).value > 0 ) ) {
		if( get( 'prodlist' ).value > 0 ) prodId = get( 'prodlist' ).value; 
		if( get( 'prodlistarticle' ).value > 0 ) prodId = get( 'prodlistarticle' ).value;
		ajax.post( 'admin/orders/easyorder/addprod', {szallitasi_mod: get( 'szallitasi_mod' ).value,prod: prodId ,pieces: get( 'pieces' ).value } );
	}
 	else alert( 'Darabszám és termék kötelező' );
}

WebShopUtil.prototype.changeToSelectedEvent = function( view , idName ) {
	if( this.prevSelectedEventCellId != '' ) {			// volt előzőleg már választás
		if( get( this.prevSelectedEventCellId ) != null ) {				// létezik az a td
			get( this.prevSelectedEventCellId ).className = this.prevSelectedEventCellClass;		// visszaállítjuk az eredeti classt
		}
		
		this.prevSelectedEventCellId = this.prevSelectedEventCellClass = '';						// visszaállítjuk alapállapotba
	}
	
	if( get( idName ) != null ) {
		this.prevSelectedEventCellId = this.actualSelectedTimeCellId = idName;
		this.prevSelectedEventCellClass = get( idName ).className;
		
		get( idName ).className = 'cell_color_weeklyview_selected';
	}

}
WebShopUtil.prototype.setEventActualWeek = function( year , weekNo ) {
	this.actualWeek = weekNo;
	this.actualYear = year;
}

WebShopUtil.prototype.selectEventLocation = function( selectedLocationId , prodId , dontAllowedMsg , changeUrlPart ) {
	if( selectedLocationId == 0 ) {
		this.actualSelectedLocationId = 0;
		this.actualSelectedTimeCellId = '';
		get( 'eventTableContainer' ).innerHTML = '';
		alert( dontAllowedMsg );
	} else {
		this.actualSelectedLocationId = selectedLocationId;
		this.prevSelectedEventCellId = this.actualSelectedTimeCellId = '';			// váltáskor nullázuk a kiválasztott, mivel lehet, hogy az időközök is változnak a helyszíntől függően
		var mode = 'public';
		if( typeof( changeUrlPart ) == 'boolean' ) {
			if( changeUrlPart ) mode = 'admin';
		}
		if( mode == 'admin' ) {
			if( ( this.actualYear == 0 ) || ( this.actualWeek == 0 ) ) ajax.post( mode + '/orders/jump/week/today/' + this.actualSelectedLocationId , { productId: prodId , changeUrlTo: mode } );		// a mai naphoz ugorjon
			else ajax.post( mode + '/orders/jump/week/' + this.actualYear + '/' + this.actualWeek + '/' + this.actualSelectedLocationId , { productId: prodId , changeUrlTo: mode } );
		} else {
			if( ( this.actualYear == 0 ) || ( this.actualWeek == 0 ) ) ajax.post( mode + '/events/jump/week/today/' + this.actualSelectedLocationId , { productId: prodId , changeUrlTo: mode } );		// a mai naphoz ugorjon
			else ajax.post( mode + '/events/jump/week/' + this.actualYear + '/' + this.actualWeek + '/' + this.actualSelectedLocationId , { productId: prodId , changeUrlTo: mode } );
		}
	}
}

WebShopUtil.prototype.eventCellOnMouseOver = function( event , td , mode ) {
	if( mode == 'show' ) {
		if( get( td.id ) != null ) {
			var left = td.offsetLeft;
			var top = td.offsetTop;
			var className = get( td.id ).className.split( '_' );
			var divIdToUse = '';
			switch( className[ className.length - 1 ] ) {
				case 'occupied':
					divIdToUse = 'eventCellOnMouseOver_occupied';
					break;
				case 'empty':
					divIdToUse = 'eventCellOnMouseOver_empty';
					break;
				case 'selected':
					divIdToUse = 'eventCellOnMouseOver_selected';
					break;
				case 'notallowed':
					divIdToUse = 'eventCellOnMouseOver_notallowed';
					break;
				case 'notallowedpast':
					divIdToUse = 'eventCellOnMouseOver_notallowedpast';
					break;
				case 'notallowedearly':
					divIdToUse = 'eventCellOnMouseOver_notallowedearly';
					break;
				case 'adminempty':
					divIdToUse = 'eventCellOnMouseOver_adminempty';
					break;
				case 'adminoccupied':
					divIdToUse = 'eventCellOnMouseOver_adminoccupied';
					break;
			}

			if( event.pageX || event.pageY ) {
//				get( divIdToUse ).style.left = ( event.pageX ) + 'px';
//				get( divIdToUse ).style.top = ( event.pageY ) + 'px';
//				get( divIdToUse ).style.left = ( left + 70 ) + 'px';
//				get( divIdToUse ).style.top = ( top + 270 ) + 'px';
				if( location.href.indexOf( 'admin/' ) == -1 ) get( divIdToUse ).style.left = ( left + 60 ) + 'px';
				else get( divIdToUse ).style.left = ( left + get( 'tableDivContainer' ).offsetLeft + 60 ) + 'px';
				get( divIdToUse ).style.top = ( top + get( 'tableDivContainer' ).offsetTop + 50 ) + 'px';
				get( divIdToUse ).style.visibility = 'visible';
			} else if( event.clientX || event.clientY ) {		// ie7 & ie8
//				get( divIdToUse ).style.left = ( event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - 230 ) + 'px';
//				get( divIdToUse ).style.top = ( event.clientY + document.body.scrollTop + document.documentElement.scrollTop - 280 ) + 'px';
//				get( divIdToUse ).style.left = ( left + 70 ) + 'px';
//				get( divIdToUse ).style.top = ( top + 270 ) + 'px';
				if( location.href.indexOf( 'admin/' ) == -1 ) get( divIdToUse ).style.left = ( left + 60 ) + 'px';
				else get( divIdToUse ).style.left = ( left + get( 'tableDivContainer' ).offsetLeft + 60 ) + 'px';
				get( divIdToUse ).style.top = ( top + get( 'tableDivContainer' ).offsetTop + 50 ) + 'px';
				get( divIdToUse ).style.visibility = 'visible';
			}
			
		}
	} else if( mode == 'hide' ) {
		if( get( 'eventCellOnMouseOver_occupied' ) != null ) get( 'eventCellOnMouseOver_occupied' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_empty' ) != null ) get( 'eventCellOnMouseOver_empty' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_selected' ) != null ) get( 'eventCellOnMouseOver_selected' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_notallowed' ) != null ) get( 'eventCellOnMouseOver_notallowed' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_notallowedpast' ) != null ) get( 'eventCellOnMouseOver_notallowedpast' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_notallowedearly' ) != null ) get( 'eventCellOnMouseOver_notallowedearly' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_adminempty' ) != null ) get( 'eventCellOnMouseOver_adminempty' ).style.visibility = 'hidden';
		if( get( 'eventCellOnMouseOver_adminoccupied' ) != null ) get( 'eventCellOnMouseOver_adminoccupied' ).style.visibility = 'hidden';
	}
}

WebShopUtil.prototype.eventGoToOrderEnabled = function( locEnabled , timeEnabled ) {
	var isLocOk = isTimeOk = false;
	if( locEnabled && ( this.actualSelectedLocationId != 0 ) ) isLocOk = true;
	if( timeEnabled && ( this.actualSelectedTimeCellId != '' ) ) isTimeOk = true;
	
	if( locEnabled && timeEnabled ) {
		if( isLocOk && isTimeOk ) return true;
		else return false;
	} else if( locEnabled ) return isLocOk;
	else if( timeEnabled ) return isTimeOk;
	else return false;
}

WebShopUtil.prototype.showEventOccupied = function( eventMode , selectedCell ) {
	ajax.load( '#admin/orders/showordersfortime' , { mode: eventMode , locationId: this.actualSelectedLocationId , cellId: selectedCell } );
}
