var registration_alt_emails_counter = 0;
var cp = null;
var cCal = null;

var MainMenu = new Array('home', 'models', 'erosblog', 'search', 'stockroom', 'forum', 'calendar', 'signup', 'affiliate');
var CurrentMenu = null;
var CurrentTab = null;
var PrevMenu = $('sm-' + MainMenu[0]);
var PrevTab = $('mm-' + MainMenu[0]);
var timer = null;

function Popup(url)
{
	window.open(url);
}

function BaloonShow(id, e, offset_x, offset_y)
{
	if(!offset_x) {
		offset_x =0;
	}
	if(!offset_y) {
		offset_y = 0;
	}
	
	$(id).style.display = 'block';
	$(id).style.top = Event.pointerY(e) + offset_y + 'px';
	$(id).style.left = Event.pointerX(e) + offset_x + 'px';
}

function BaloonHide(id) {
	$(id).style.display = 'none';
}

function RemoveAccount() {
	axLoadContent('/profile.html?S2XEvent=RemoveAccount', 'content-container');
}

function CancelAccount() {
	axLoadContent('/profile.html?S2XEvent=ContinueCancelAccount', 'content-container');
}

function AddToFavorites(url) {
	axPut('favorites', 'Adding to My Collections. Please wait...');
	axLoadContent(url+'?S2XEvent=AddToFavorites', 'favorites', 3);
}

function ClearHistory(type, id) {
	switch(type) {
		case 'downloads':
			axLoadContent('/profile.html?S2XEvent=ClearDownloadsHistory&id=' + id, '');

			new Ajax('/profile.html?S2XEvent=History&type=' + history, {method: 'get', update: $('history-container'), evalScripts: true}).request().addEvent('onComplete', function(){
				var fxx = new Fx.Styles('history-container', {duration: 500, wait: false});
				fxx.start({'opacity': 1});
			});
		break;
		
		case 'billing':
			axLoadContent('/profile.html?S2XEvent=ClearBillingHistory&id=' + id, 'content-container');
		break;
		
		case 'favorites':
			axLoadContent('/profile.html?S2XEvent=ClearFavorites&id=' + id, 'content-container');
		break;
	}
}

function LoadTopPics(type, page) {
	new Ajax('/?S2XEvent=LoadTopPics&type=' + type + '&page=' + page, {method: 'get', update: $('top-pics'), evalScripts: true}).request();
}

function OpenWindow(url) {
	window.open(url);
}

function SubmitForm() {
	axSubmitForm($('form'), function(){
	
		var form = $('form')
		var width = form.getWidth();
		var height = form.getHeight();
		form.innerHTML = '';
		form.className = 'loading';
		form.style.width = width + 'px';
		form.style.height = height + 'px';
	
		if(axCheckResponse()) {
			axPut('content-container', axResponse());
		}
	}, 'all');
	 
	return false;
}

function SubmitComment() {
	axSubmitForm($('form'), function(){
		var form = $('form')
		var width = form.getWidth();
		var height = form.getHeight();
		form.innerHTML = '';
		form.className = 'loading';
		form.style.width = width + 'px';
		form.style.height = height + 'px';
	
		if(axCheckResponse()) {
			axPut('form-container', axResponse());
		}
	}, 'all');
	 
	return false;
}

function RegistrationAddAltEmail() {
	if(registration_alt_emails_counter >= 2){
		alert('You can not add more then 2 alternative email addresses!');
		return;
	}
	new Insertion.After('alt-email-container', '<input type="text" name="alt_email[' + registration_alt_emails_counter + ']" />');
	registration_alt_emails_counter++;
}

function AddMoreLinks() {
	new Insertion.After(document.getElementById('links'), '<div class="row"><input type="text" name="links[]" /></div>');
	registration_alt_emails_counter++;
}

function NewAltEmail() {
	if(registration_alt_emails_counter >= 2){
		alert('You can not add more then 2 alternative email addresses!');
		return;
	}
	holder = (document.getElementById('alt-inp-' + (registration_alt_emails_counter)) ? 'alt-inp-' + (registration_alt_emails_counter) : 'alt-email-container' );
	new Insertion.After(holder, '<div class="row" id="alt-inp-' + (registration_alt_emails_counter + 1) + '"><label>Alt. Email</label><input type="text" name="alt_email[]" /><button type="button" onclick="RemoveAltEmail(\'alt-inp-' + (registration_alt_emails_counter + 1) + '\')">Remove</button></div>');
	registration_alt_emails_counter++;
}

function RemoveAltEmail(id){
	document.getElementById(id).parentNode.removeChild(document.getElementById(id));	
	registration_alt_emails_counter--;
}

function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}

function ClearInput(id, def_val) {
	var input = document.getElementById(id);
	if(input) {
		if(input.value == def_val) {
			input.value = '';
		}
	}
}

function FillInput(id, def_val) {
	var input = document.getElementById(id);
	if(input) {
		if(input.value == '') {
			input.value = def_val;
		}
	}
}

function ToggleFAQCategory(item_id) {
	var item = document.getElementById(item_id);
	
	if(item) {
		if(item.className == 'expanded') {
			item.className = ''
		} else {
			item.className = 'expanded'
		}
	}
}

function SelectAllOptions(select_id) {
	var select = document.getElementById(select_id);
	if(select) {
		for( var i = 0; i < select.options.length; i++) {
			select.options[i].selected = true;
		}
	}
}

window.onload = function() {
	InitMainMenu();
	InitHelpPopups();
	InitRatings();
	InitFavAccordion();
	
	if($('layered-form')) {
		$('layered-form').onsubmit = LoginSubmit;
	}

	if($('model-layered-form')) {
		$('model-layered-form').onsubmit = ModelLoginSubmit;
	}

	if($('request-model')) {
		$('request-model').onsubmit = RequestModel;
	}
	
	if($('history-selector')){
		$('history-selector').onchange = SelectHistory;
	}
}

function RequestModel(){
	$('request-model').send({update: null, onComplete: function (request) { ModelRequested(request); }});
	
	return false;
}

function ModelRequested(request){
	if(request != ''){
		DisplayError(request);
	} else {
		$('error-msg').setStyle('display', 'none');
		var fx = new Fx.Styles('request-model', {duration: 1000, wait: false});
		var fy = new Fx.Styles('thank-you', {duration: 1000, wait: false});
		fx.start({'opacity': 0}).addEvent('onComplete', function () {
			$('request-model').setStyle('display', 'none');
			$('thank-you').setStyle('opacity', 0);
			$('thank-you').setStyle('display', 'block');
			fy.start({'opacity': 1});
		});
		
	}
}

function SelectHistory(){
	var history = this.value;
	var fx = new Fx.Styles('history-container', {duration: 1000, wait: false});
	fx.start({'opacity': 0}).addEvent('onComplete', function () {
		$('history-title').setHTML(history + ' History');
		new Ajax('/profile.html?S2XEvent=History&type=' + history, {method: 'get', update: $('history-container'), evalScripts: true}).request().addEvent('onComplete', function(){
			var fxx = new Fx.Styles('history-container', {duration: 500, wait: false});
			fxx.start({'opacity': 1});
		});
	});
}

function InitLoginForm(){
	$('layered-form').onsubmit = LoginSubmit;
	$('model-layered-form').onsubmit = ModelLoginSubmit;
	
	return true;
}

function LoginSubmit(){
	$('layered-form').send({update: null, onComplete: function (request) { FormCallback(request); }});

	return false;
}

function ModelLoginSubmit(){
	$('model-layered-form').send({update: null, onComplete: function (request) { ModelFormCallback(request); }});

	return false;
}

function ModelFormCallback(request){
	FormCallback(request, 'model-error-msg');
}

function FormCallback(request, form_type){
	if (request == 'ok'){
		if(form_type == 'model-error-msg'){
			window.location.href = '/models-area/';
		} else {
			window.location.href = unescape(window.location.pathname);
		} 
	} else {
		DisplayError('Entered email or password is not valid! Please try again.', form_type);
	}
}

function InitFavAccordion(){
	if(!$('accordion')){ return; }
	var accordion = new Accordion('h3.atStart', 'div.atStart', {
		opacity: true,
		onActive: function(toggler, element){
			toggler.setStyle('backgroundImage', 'url(./public/images/accordion/item-sel-bg.gif)');
			toggler.setStyle('borderBottom', '2px solid #D7D7D7');
		},
	 
		onBackground: function(toggler, element){
			toggler.setStyle('backgroundImage', 'url(./public/images/accordion/item-bg.gif)');
			toggler.setStyle('borderBottom', '2px solid #F3F3F3');
		}
	}, $('accordion'));
	
	$$('.fav-tabs A').each(function(el){ 
		el.onclick = function () {
			new Ajax(el.href, {method: 'get', update: $(el.rel), evalScripts: true}).request();
			$$('UL#' + el.getParent().getParent().id + ' LI').each (function(el){ el.className = ''; });
			this.getParent().className = 'selected';
			el.getParent().getParent().getParent().setStyle('height', 'auto');

			return false;
		}
	});
}

function InitRatings() {
	$$('.rate').each(function(element,i){
        element.addEvent('click', function(){
	        var myStyles = ['nostar', 'onestar', 'twostar', 'threestar', 'fourstar', 'fivestar'];
	        myStyles.each(function(myStyle){
	            if(element.getParent().hasClass(myStyle) && !element.getParent().hasClass('disabled')){
	                element.getParent().removeClass(myStyle)
	            }
	        });            
	        myStyles.each(function(myStyle, index){
	        	pos = element.getChildren()[0].rel;
	            if(index == pos){
	                element.getParent().toggleClass(myStyle);
	                Vote(pos, element.getParent().id);
	            }
	        });            
        });
	});
}

function Vote(rating, update_id) { 
	vals = update_id.split('-');
	new Ajax('/?S2XEvent=Vote&rating=' + rating + '&media_id=' + vals[1], {method: 'get', update: $(update_id), evalScripts: true}).request();
}

function CloseMessage() {
	document.getElementById('atf').style.display = 'none';
}

function PickerHover(val, color) {
	if (val.relate.search('-bg') != -1){
		$(val.relate).style.backgroundColor = color;
	} else {
		$(val.relate).style.color = color;
	}
}

function InitPage() {
	cp = new ColorPicker();
    $('inp-header-bg').relate = 'prv-header-bg';
    $('inp-header-menu').relate = 'prv-header-menu';
    $('inp-body-bg').relate = 'prv-body-bg';
    $('inp-body-menu').relate = 'prv-body-menu';
}

function PreviewFont(obj, rel) {
	$(rel).style.fontFamily = obj.options[obj.selectedIndex].value;
}

function CustResetToDefault() {
    $('inp-header-bg').value = '#8A0512';
    $('inp-header-menu').value = '#FFFFFF';
    $('inp-body-bg').value = '#FFFFFF';
    $('inp-body-menu').value = '#8A0512';
    
    $('prv-header-bg').style.backgroundColor = '#8A0512';
    $('prv-header-menu').style.color = '#FFFFFF';
    $('prv-body-bg').style.backgroundColor = '#FFFFFF';
    $('prv-body-menu').style.color = '#8A0512';
}

function OpenPopup(url) {
	newwindow = window.open(url, 'name', 'height=30, width=270');
	if (window.focus) {newwindow.focus()}
}

function OpenPopupPhoto(url) {
	newwindow = window.open(url, 'name', 'height = 605, width = 650');
	if (window.focus) {newwindow.focus()}
}

function findPosX(obj) {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if(obj.offsetParent)
        while(1) {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}

var aps = null;
var api = null;
var ap  = null;

function ToggleAbout(obj) {
	if(!aps || !api || !ap || !fd) {	
		$('am-photo-src').setStyle('position', 'absolute');
		$('am-photo-src').setStyle('display', 'block');
		$('am-photo-src').setStyle('visibility', 'hidden');
		
		$('full-description').setStyle('position', 'absolute');
		$('full-description').setStyle('display', 'block');
		$('full-description').setStyle('visibility', 'hidden');

		
		aps = $('am-photo-src').getCoordinates();
		api = $('am-photo-img').getCoordinates();
		ap = $('am-block').getCoordinates();
		
		$('full-description').setStyle('width', 775 - aps['width'] - 100);
		fd = $('full-description').getCoordinates();
	}
	
	if(!obj.state || obj.state == 'collapsed'){
		ExpandAboutBlock();
		obj.state = 'expanded';
		$('btn-more').src = $('btn-more').src.replace('more', 'less');
		
	} else {
		CollapseAboutBlock();
		obj.state = 'collapsed';
		$('btn-more').src = $('btn-more').src.replace('less', 'more');
	}
}

function ExpandAboutBlock(){
	/*	Definitions */
	
	fx = new Fx.Styles('am-block', {duration: 500, wait: false});
	fx_ai = new Fx.Styles('am-info', {duration: 100, wait: false});
	fx_photo = new Fx.Styles('am-photo-img', {duration: 500, wait: false});
	
	/*	Implementations	*/
	
	$('am-photo').className = 'photo-left';
	$('am-block').setStyle('width', ap['width']);
	
	fx.start({'width': 775, 'height': (aps['height'] > fd['height'] ? aps['height'] : fd['height']) + 80}).addEvent('onComplete', function(){
		$('full-description').setStyle('visibility', 'visible');
		$('short-description').setStyle('visibility', 'hidden');
		$('short-description').setStyle('position', 'absolute');
		$('full-description').setStyle('position', 'relative');
		$('am-block').setStyle('paddingBottom', '20px');
	});
	
	fx_photo.start({'width': aps['width'], 'height': aps['height']}).addEvent('onComplete', function(){
		$('am-photo-src').setStyle('width', aps['width']);
		$('am-photo-src').setStyle('height', aps['height']);
		$('am-photo-img').setStyle('position', 'absolute');
		$('am-photo-src').setStyle('position', 'relative');
		$('am-photo-src').setStyle('visibility', 'visible');
		$('am-photo-src').setStyle('display', 'block');
		$('am-photo-img').setStyle('display', 'none');
		$('am-info').setStyle('width', (725 - aps['width']));
	});
}

function CollapseAboutBlock(){
	fxphoto = new Fx.Styles('am-photo-src', {duration: 500, wait: false});
	fxam = new Fx.Styles('am-block', {duration: 500, wait: false});
	fxaminfo = new Fx.Styles('am-info', {duration: 500, wait: false});
	fxphoto.start({'width': api['width'], 'height': api['height']}).addEvent('onComplete', function(){
		$('am-photo-img').setStyle('position', 'relative');
		$('am-photo-src').setStyle('position', 'absolute');
		$('am-photo-img').setStyle('display', 'block');
		$('am-photo-src').setStyle('display', 'none');
		$('am-photo-img').setStyle('width', api['width']);
		$('am-photo-img').setStyle('height', api['height']);
		$('am-photo-img').setStyle('visibility', 'visible');
		$('am-photo-src').setStyle('visibility', 'hidden');
		$('am-photo-img').setStyle('margin', 'auto');
		
		$('short-description').setStyle('visibility', 'visible');
		$('full-description').setStyle('visibility', 'hidden');
		$('full-description').setStyle('position', 'absolute');
		$('short-description').setStyle('position', 'relative');
		$('short-description').setStyle('width', 'auto');

		$('am-photo').className = '';
	});
	fxaminfo.start({'width': ap['width'] - 20});
	fxam.start({'width': ap['width'], 'height': ap['height']});
}

function InitHelpPopups() {
	var list = document.getElementsByTagName('a');
	for(i = 0; i < list.length; i++){
		if(list[i].rel.toLowerCase() == 'popup'){
			list[i].onmouseover = ShowBaloon;
			list[i].onmouseout = HideBaloon;
		}
		if(list[i].rev.toLowerCase() == 'toggle'){
			StartToggleBlock(list[i]);		
		}
	}
} 

function StartToggleBlock(obj){
	if(obj.slider){ return; }
	obj.onclick = TBClicked;
	obj.href = 'javascript:;';
	obj.cookie = new Hash.Cookie(obj.rel);
	obj.slider = new Fx.Slide(obj.rel);
	
	if(obj.cookie.get('state') == 'collapsed'){
		obj.slider.slideOut();
		obj.childNodes[0].src = obj.childNodes[0].src.replace('collapse', 'expand');
	}
}

function TBClicked(){
	if(!$(this.rel)) { return; }
	
	this.state = this.cookie.get('state');

	if(this.state == 'expanded' || !this.state){
		this.cookie.extend({'state': (this.state = 'collapsed')});
		this.slider.slideOut();
		this.childNodes[0].src = this.childNodes[0].src.replace('collapse', 'expand');
	} else {
		this.cookie.extend({'state': (this.state = 'expanded')});
		this.slider.slideIn();
		this.childNodes[0].src = this.childNodes[0].src.replace('expand', 'collapse');
	}

	return;
}

function ShowBaloon() {
	if(!this.active) {
		var items = this.rev.split('###');
		$('hlp-frame').setStyle('opacity', 0);
		$('hlp-frame').setStyle('display', 'block');
		$('bl-title').setHTML(items[0]);
		$('bl-message').setHTML(items[1]);
	
		if(this.getFirst()){
			AdjustBaloon(this.getFirst(), $('hlp-frame'));
		} else {
			AdjustBaloon(this, $('hlp-frame'));
		}
	
		var fx = new Fx.Styles($('hlp-frame'), {duration: 200, wait: false});
		fx.start({'opacity': 1});
	} else {
		this.active = true;
	}
}

function AdjustBaloon(control, baloon) {
	control.id = $random(1, 1000);
	var obj = $(control.id);
	
	var baloon_coords = baloon.getCoordinates();
	var control_coords = obj.getCoordinates();
	
	if((baloon_coords['width'] + control_coords['left']) > (getHW('width') - 30)){
		if ((baloon_coords['height'] + control_coords['top']) > getHW('height')){
			baloon.className = 'baloon tail-br';
			baloon.setStyle('top', (control_coords['top'] - baloon_coords['height']) + 10);
			baloon.setStyle('left', (control_coords['left'] - baloon_coords['width']) + 20);
		} else {
			baloon.className = 'baloon tail-tr';
			baloon.setStyle('top', (control_coords['bottom']) - 5);
			baloon.setStyle('left', (control_coords['left'] - baloon_coords['width']) + 20);
		} 		
	} else {
		if ((baloon_coords['height'] + control_coords['top']) > getHW('height')){
			baloon.className = 'baloon tail-bl';
			baloon.setStyle('top', (control_coords['top'] - baloon_coords['height']) + 10);
			baloon.setStyle('left', (control_coords['right']) - 20);
		} else {
			baloon.className = 'baloon tail-tl';
			baloon.setStyle('top', (control_coords['bottom']) - 5);
			baloon.setStyle('left', (control_coords['right']) - 20);
		} 		
	}
}

function getHW(size) {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  if(size == 'height'){
	  return myHeight;
  } else {
	  return myWidth;
  }
}

function HideBaloon() {
	this.active = false;
	$('hlp-frame').setStyle('display', 'none');
}

function passwordChanged(pwd) {
	var strength = document.getElementById('strength');
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");
	
	if (pwd.value.length == 0) {
		strength.className = 'pass-strength';
	} else if (false == enoughRegex.test(pwd.value)) {
		strength.className = 'pass-strength l1';
	} else if (strongRegex.test(pwd.value)) {
		strength.className = 'pass-strength l3';
	} else if (mediumRegex.test(pwd.value)) {
		strength.className = 'pass-strength l2';
	} else {
		strength.className = 'pass-strength l1';
	}
}

function InitMainMenu() {
	var sz = MainMenu.length;
	for(i = 0; i < sz; i++){
		if(elem = $('mm-' + MainMenu[i])){
			elem.rel = ('sm-' + MainMenu[i]);
			elem.onmouseover = elem.onmousemove = ShowSubMenu;
			elem.onmouseout = $('subheader').onmouseout = HideSubMenu;
			$('subheader').onmouseover = $('subheader').onmousemove = function (){ clearTimeout(timer); }
			if(elem.parentNode.className == 'selected'){
				PrevTab = elem.parentNode; 
				PrevMenu = $(elem.rel); 
			}
		}
	}
}

function ShowSubMenu() {
	clearTimeout(timer);
	DelayMenu();
	HideItem(PrevMenu, PrevTab);
	if(sm = $(this.rel)){
		CurrentMenu = sm;
		CurrentTab = this.parentNode;
		ShowItem(CurrentMenu, CurrentTab);
	}
}

function HideSubMenu() {
	timer = setTimeout(DelayMenu, 1000);
}

function DelayMenu() {
	HideItem(CurrentMenu, CurrentTab);
	ShowItem(PrevMenu, PrevTab);
}

function HideItem(menu, tab) {
	if (menu) { menu.setStyle('display', 'none'); }
	if (tab) { tab.className = ''; }
}

function ShowItem(menu, tab) {
	if (menu) { menu.setStyle('display', 'block'); }
	if (tab) { tab.className = 'selected'; }
}

var el_timer = null;

function ShowCategoriesList(obj) {
	if(!obj.state) {
		$(obj.rel).addEvent('mousemove', function(){clearTimeout(el_timer);});
		obj.addEvent('mouseout', function(){
			el_timer = setTimeout(function(){obj.state = 'closed'; HideElement(obj.rel);}, 1000);
		});
		$(obj.rel).addEvent('mouseout', function(){
			el_timer = setTimeout(function(){obj.state = 'closed'; HideElement(obj.rel);}, 1000);
		});
	}
	if(obj.state != 'opened') {
		DisplayElement(obj.rel, findPosX(obj) + 52, findPosY(obj) + 20);
		obj.state = 'opened';
	} else {
		HideElement(obj.rel);
		obj.state = 'closed';
	}
	
}

function DisplayElement(id, pos_x, pos_y) {
	clearTimeout(el_timer);
	$(id).setStyle('left', pos_x + 'px');
	$(id).setStyle('top', pos_y + 'px');
	height = $(id).getStyle('height');
	$(id).setStyle('height', 0);
	$(id).setStyle('width', 0);
	$(id).setStyle('display', 'block');
	fx = new Fx.Styles($(id), {duration: 200, wait:false});
	fxx = new Fx.Styles($(id), {duration: 200, wait:false});
 	fx.start({'width': 250});
	fxx.start({'height' : height}).addEvent('onComplete', function(){
		$(id).setStyle('height', 'auto');
	});
}

function  HideElement(id) {
	clearTimeout(el_timer);
	hfx = new Fx.Styles($(id), {duration: 200, wait: false});
 	hfx.start({'opacity': 0}).addEvent('onComplete', function(){
		$(id).setStyle('display', 'none');
		$(id).setStyle('height', '200px');
		$(id).setStyle('width', '200px');
		$(id).setStyle('opacity', 1);
	});
}

function AddAltEmail() {
	if(registration_alt_emails_counter >= 2){
		alert('You can not add more then 2 alternative email addresses!');
		return;
	}
	var AltEmail = new Element('input', { 'type': 'text', 'name': 'alt_email[]' });
	AltEmail.inject($('alt-email-container'));
	registration_alt_emails_counter++;
}

function SubmitRegistrationForm() {
	var log = $('log_res').addClass('ajax-loading');
	$('reg-form').send({update: null, onComplete: function (request) {ContactFormCallback(request); }});
	return false;
}

function SubmitPaymentForm() {
	var log = $('log-res').addClass('ajax-loading');
	$('payment-form').send({update: null, onComplete: function (request) {GotoStep3(request); }});
	return false;
}

function ContactFormCallback(request) {
	$('log_res').removeClass('ajax-loading');
	if((error = ProcessResponse(request)) != ''){
		DisplayError(error);
	} else {
		GotoStep2();
	}
}

function ProcessResponse(msg) {
	list = msg.split(':');
	if (list[0] == 'ERROR'){
		return list[1];
	} else {
		return '';
	}
}

function DisplayError(error, id) {
	if(id != 'model-error-msg') { id = 'error-msg' }
	$(id).setHTML(error);
	$(id).setStyle('opacity', 0);
	$(id).setStyle('display', 'block');
	
	var fx = new Fx.Styles($(id), {duration: 1000, wait: false});
	fx.start({'opacity': 1});
}

function GotoStep2(){
	var fx = new Fx.Styles($('error-msg'), {duration: 1000, wait: false});
	fx.start({'opacity': 0}).addEvent('onComplete', function(){
		$('error-msg').setStyle('display', 'none');
	});
	
	var step1 = new Fx.Styles($('step-1'), {duration: 1000, wait: false});
	var step2 = new Fx.Styles($('step-2'), {duration: 1000, wait: false});
	
	step1.start({'opacity': 0}).addEvent('onComplete', function(){
		$('step-2').setStyle('opacity', 0);
		$('step-2').setStyle('display', 'block');
		
		$('step-1').setStyle('display', 'none');
		$('current-step').className = 'mark step-2';
		$('step-info').className = 'step-info step-2';

		step2.start({'opacity' : 1});
	});
}

function GotoStep3(){
	var fx = new Fx.Styles($('error-msg'), {duration: 1000, wait: false});
	fx.start({'opacity': 0}).addEvent('onComplete', function(){
		$('error-msg').setStyle('display', 'none');
	});
	
	var step2 = new Fx.Styles($('step-2'), {duration: 1000, wait: false});
	var step3 = new Fx.Styles($('step-3'), {duration: 1000, wait: false});
	
	step2.start({'opacity': 0}).addEvent('onComplete', function(){
		$('step-3').setStyle('opacity', 0);
		$('step-3').setStyle('display', 'block');
		
		$('step-2').setStyle('display', 'none');
		$('current-step').className = 'mark step-3';
		$('step-info').className = 'step-info step-3';

		step3.start({'opacity' : 1});
	});
}

function ShowModelLogin(){
	$('sign-in').setStyle('display', 'none');
	ShowLogin('model-');
	
	return false;
}

function ShowLogin(type){
	if(!type) { type = ''; }
	if(type == ''){
		$('model-sign-in').setStyle('display', 'none');
	}
	frame = (type + 'sign-in');

	$(frame).setStyle('opacity', 0);
	$(frame).setStyle('display', 'block');
	
	$(frame).setStyle('left', (getWidth() / 2) - 200);
	$(frame).setStyle('top', (getHeight() / 2) - 125);
	
	var fx = new Fx.Styles($(frame), {duration: 1000, wait: false});
	fx.start({'opacity': 1}).addEvent('onComplete', function(){
		$(type + 'email').focus();
	});
	
	return false;
}

function CloseFrame(id){
	
	var fx = new Fx.Styles($(id), {duration: 500, wait: false});
	fx.start({'opacity': 0}).addEvent('onComplete', function(){
		$(id).setStyle('display', 'none');
	});

	return false;	
}

function addToCart(id) {
	new Ajax('/?S2XEvent=AddToCart&media_item=' + id, {method: 'get', update: $('cart-container'), evalScripts: true}).request().addEvent('onComplete', function(){
		ShowFrame('cart-added');
	});
}

function DeleteCollection(obj, id){
	var accParent = obj.getParent().id;
	var fx = new Fx.Styles($(accParent), {duration: 500, wait: false});
	var fxe = new Fx.Styles($('element-' + accParent), {duration: 500, wait: false});
	 
	if(window.confirm('Do you really want to remove collection of this model?\nPlease, note that you will NOT be able to undo this action.')){
		new Ajax('/profile.html?S2XEvent=DeleteCollection&model=' + id, {method: 'get', update: $('history-container'), evalScripts: true}).request().addEvent('onComplete', function(){
			fx.start({'opacity': 0}).addEvent('onComplete', function(){
				$(accParent).setStyle('display', 'none');		
			});
			fxe.start({'opacity': 0}).addEvent('onComplete', function(){
				$('element-' + accParent).setStyle('display', 'none');
			});
		});
	}
}

function UseRange(obj){
	$('end-date').setStyle('display', (obj.checked ? 'block' : 'none'));
}

function RemoveSelectedDates(){
	items = ($('dates-list').options.length - 1);
	for(i = items; i > -1; i--) {
		if($('dates-list').options[i].selected == true) {
			$('dates-list').remove(i);
		}
	}
}

function ClearDatesList(){
	items = $('dates-list').options.length - 1;
	for(i = items; i > -1; i--) {
		$('dates-list').remove(i);
	}
}

function AddDateToList(){
	$('error-msg').setStyle('display', 'none');
	
	if($('use-range').checked){
		// Check, is date_from more than current date and less than date_to
		if(CompareDates('today', $('calendar_from').value)) {
			if(CompareDates($('calendar_from').value, $('calendar_to').value)) {
				// Add dates range to the list
				Put2List($('calendar_from').value + '-' + $('calendar_to').value);
			} else {
				DisplayError('Start Date should be less than End Date.');
			}
		} else {
			DisplayError('Start Date should be greater than Current Date');
		}
	} else {
		// Is date more than current date?
		if(CompareDates('today', $('calendar_from').value)){
			// Add date to the list
			Put2List($('calendar_from').value);
		} else {
			DisplayError('Start Date should be greater than Current Date.');
		}
	}
	
}

function Put2List(str){
	// If date already in list, display error
	items = ($('dates-list').options.length - 1);
	for(i = items; i > -1; i--) {
		if($('dates-list').options[i].value == str) {
			DisplayError('Date already in the list.');
			return;
		}
	}
	
	var NewOption = document.createElement('option');
	NewOption.text = str;
	NewOption.value = str;
	try {
		$('dates-list').add(NewOption, null); // standards compliant; doesn't work in IE
	} catch(ex) {
		$('dates-list').add(NewOption); // IE only
	}
}

function CompareDates(date1, date2){ // Put dates in format mm/dd/yyyy, for today use "today"
	//alert('Comparing: ' + ParseDate(date2) + ' > ' + ParseDate(date1));
	return (ParseDate(date2) >= ParseDate(date1));
}

function ParseDate(date_val){
	if(date_val.toLowerCase() == 'today'){
		date_val = new Date();
	} else {
		date_val = date_val.split('/');
		date_val = new Date(parseInt((date_val[2] > 2015 ? 1990 : date_val[2])), (parseInt(((date_val[0] - 1) > 12 ? 1 : (date_val[0] - 1)))), parseInt((date_val[1] > 31 ? 1 : date_val[1])), 23, 59, 59);
	}

	return date_val;
}

function InitCalendar(dates, model){
	cCal = new CALENDAR();
	cCal.model = model;
	eval('cCal.AvailableDates = [' + dates + '];');
	UpdateCalendar();
}

function UpdateCalendar(){
	$('calendar-control').setHTML(cCal.create());
}

function LoadPrevMonth(){
	if (!cCal) { return; }
	if (cCal.month == 1){
	 	cCal.month = 12;
	 	cCal.year = (cCal.year - 1) 
	} else {
		cCal.month = (cCal.month - 1);
	} 
	UpdateCalendar();
}

function LoadNextMonth(){
	if (!cCal) { return; }
	if (cCal.month == 12){
	 	cCal.month = 1;
	 	cCal.year = (cCal.year + 1) 
	} else {
		cCal.month = (cCal.month + 1);
	} 
	UpdateCalendar();
}

function CalendarFormCallback(request){
	if(request.toLowerCase() != 'ok'){
		$('post-button').disabled = false;
		DisplayError(request);
	} else {
		window.location.href = '/models-area/?S2XEvent=Calendar';
	}
}

function SubmitDates(){
	$('error-msg').setStyle('display', 'none');
	$('error-msg').setStyle('color', '#BC0000');
	
	dates = '';
	items = $('dates-list').options.length - 1;
	for(i = items; i > -1; i--) {
		dates += ($('dates-list').options[i].value + ';');
	}
	$('dates').value = dates;
	
	$('post-button').disabled = true;
	$('date-entries').send({update: null, onComplete: function (request) {CalendarFormCallback(request); }});
	
	return false;
}

function UpdateMediaList(request){
	items = $('upd-media-list').options.length - 1;
	for(i = items; i > 0; i--) {
		$('upd-media-list').remove(i);
	}	
	
	list = request.split(';');
	for(i = 0; i < list.length; i++){
		NewOption = document.createElement('option');
		vals = list[i].split('-');
		
		NewOption.text = vals[1];
		NewOption.value = vals[0];
		
		try {
			$('upd-media-list').add(NewOption, null); // standards compliant; doesn't work in IE
		} catch(ex) {
			$('upd-media-list').add(NewOption); // IE only
		}	
	}
}

function UpdateEntriesCallback(request){
	if(request.toLowerCase() == 'ok'){
		window.location.href = '/models-area/?S2XEvent=UpdateRegulations';
	} else {
		DisplayError(request);
	}
}

function ShowFrame(id) {
	$(id).setStyle('opacity', 1);
	$(id).setStyle('left', (window.getWidth() / 2) - 200);
	$(id).setStyle('top', (window.getHeight() / 2) + (window.getScrollTop() / 2));
	$(id).setStyle('display', 'block');
}

