	
	/******************* PAYPAL *******************/
	$("#paypal-buy-now-button" ).livequery('click',function(e){
		
		e.preventDefault();
		
		var process = true;
		
		if ( 
			!( $("#orderImageForm").length > 0 ) ||  
			!( $("#billing_customer_name").length > 0 ) ||  
			!( $("#billing_customer_address").length > 0 ) ||  
			!( $("#billing_save_to_profile").length > 0 ) ||  
			!( $("input[name='os0']").length > 0 ) ||  
			!( $("input[name='os1']").length > 0 ) ||  
			!( $("input[name='os2']").length > 0 ) 
		) {
			process = false;			
		}
		
		var billing_name_new = $("#billing_customer_name").val();
		var billing_address_new = $("#billing_customer_address").val();
		
		if ( billing_name_new == "" ) {
			$("#billing_customer_name").addClass('error');
			process = false;
		}
		else {
			$("#billing_customer_name").removeClass('error');
		}
		if ( billing_address_new == "" ) {
			$("#billing_customer_address").addClass('error');
			process = false;
		}
		else {
			$("#billing_customer_address").removeClass('error');
		}
		
		var billing_name_old = $("#billing_customer_name").attr('data-current-value');
		var billing_address_old = $("#billing_customer_address").attr('data-current-value');
		
		// update user profile billing iinformation
		if ( process && $("#billing_save_to_profile").is(':checked') && ( billing_name_new != billing_name_old || billing_address_new != billing_address_old ) ) {
		
			var filename = '/'+labels.lang+'/edit-profile.html';
		
		    var send = {
				'ajax': "2",
				'action': "edit-billing-profile",
				'user_billing_customer_name': billing_name_new,
				'user_billing_customer_address': billing_address_new
		    }
		    
		    var encoded = $.toJSON(send);
		    var params = $.evalJSON(encoded);
			
		    $.ajax({
				'url': filename,
				'dataType': 'json',
				'type': "POST",
				'data': params,
				'async': false,
				'success': function( json_result ) {
					if ( typeof json_result.error == 'undefined' || json_result.error ) {
						process = false;						
					}
		    	}
			});	
		
		}
		
		var order_id = $("input[name='os0']").val();
		var user_id = $("input[name='os1']").val();
		var image_id = $("input[name='os2']").val();
		
		// upadte order billing information
		if ( process ) {
			
			var filename = '/'+labels.lang+'/orderprocess.html';
			
		    var send = {
				'ajax': "2",
				'action': "update-billing",
				'order_id': order_id,
				'user_id': user_id,
				'image_id': image_id,
				'user_billing_customer_name': billing_name_new,
				'user_billing_customer_address': billing_address_new
		    }
		    
		    var encoded = $.toJSON(send);
		    var params = $.evalJSON(encoded);
			
		    $.ajax({
				'url': filename,
				'dataType': 'json',
				'type': "POST",
				'data': params,
				'async': false,
				'success': function( json_result ) {
					if ( typeof json_result.error == 'undefined' || json_result.error ) {
						process = false;						
					}
		    	}
			});	
			
		}

		// submit form
		if ( process ) {
			$("#orderImageForm").submit();
		}
		
	});

	
	/******************* LOGIN DIALOG *******************/
	$(".action-login-dialog" ).livequery('click',function(e){
		
		e.preventDefault();
		
		var filename = '/'+labels.lang+'/login.html';
		
		// TODO 
		//var $form = $(obj).parents('form');
		//var id = $form.attr('id');
		//var $licenseBlock = $form.find('#generated-code');

	    var send = {
			'ajax': "2"
	    }
	    
	    var encoded = $.toJSON(send);
	    var params = $.evalJSON(encoded);
		
		$.post(filename, params,function(response){

			// create content
			var decoded = $('<div></div>').html(response);
			var content = $('<div id="login-dialog"></div>');		
			content.html(decoded);

			// create dialog
			var dialog = content.dialog({
	            title: 'Login',
	            dialogClass: 'ngl_dialog_container',
	            autoOpen: false,
	            position: 'center',
	            height: 'auto',
	            width: 'auto',
	            modal: true,
	            draggable: false,
	            resizable: false
			});
			
			// open dialog
			if( !$('#login-dialog').dialog("isOpen") ){
				dialog.dialog('open');			
			}
			
			// destroy dialog on close	
			$("#login-dialog").bind("dialogclose", function(){
	        	$("#login-dialog").dialog('destroy');
	            $("#login-dialog").remove();
	        });
			
	   });
			
	});


	/******************* DELETE CONFIRMATION DIALOG *******************/
	function deleteNGLConfirmation( functionToCall, obj ){
		
		var content = $('<div id="del_dialog"><p><span class="" style="float:left; margin:0 7px 20px 0;"></span>This item will be permanently deleted and cannot be recovered. Are you sure?</p></div>');
	
		// create dialog
		var dialog = content.dialog({
			title: 'Confirmation',
			dialogClass: 'ngl_dialog_container',
			autoOpen: false,
			position: 'center',
			height: 'auto',
			width: 'auto',
			modal: true,
			draggable: false,
			resizable: false,
			buttons: {
				'Delete': function() {
					functionToCall( obj );
					$(this).dialog('close');
				},
				'Cancel': function() {
					$(this).dialog('close');
				}
			}
		});
	
		// open dialog
		if( !$('#del_dialog').dialog("isOpen") ){
			dialog.dialog('open');			
		}
		
		// destroy dialog on close	
		$("#del_dialog").bind("dialogclose", function(){
			$("#del_dialog").dialog('destroy');
			$("#del_dialog").remove();
		});
	}

	
// added by onno

function imposeMaxLength(Object, MaxLen)
{
    return (Object.value.length <= MaxLen);
}


/**
 * @author goldy
 */





function redirect(){
   location.reload(true);
}
function loginShowRequest(formData, jqForm, options){
	var queryString = $.param(formData);
    var warning = 'Please, wait while data is processed';
    
	show_stack_bottomleft(false, warning);
	//show_stack_bottomleft(false, queryString);

    var formid = jqForm.attr('id');
	//alert(formid);
    var patt = /\d+/g;
    
	if(formid==='imageEditForm'){
		$.blockUI({
				title: 'Please wait.',
				theme:true,
                message: '<p><span class="ui-icon ui-icon-alert" />Data is processed.</p>'
            });	
	}
	
   return true;
}
function loginShowResponse(responseText, statusText, xhr, $form){
	//debuglog(responseText);
	var json_response= $.toJSON(responseText);
	json_response = $.evalJSON(json_response);
	//debuglog(json_response.err);
	var formid = $form.attr('id');
	
	$(".loading-overlay").animate({
        opacity:0
    }, 500, function(){
        $(this).remove();
    });
    if( typeof(json_response.auth) != 'undefined' && json_response.auth.length !== 0){
        $("input[name='auth_hash']").val(json_response.auth);
    }
    
    if( typeof(json_response.err)!='undefined' && json_response.err.length!==0){
        $("p.error_p").each(function(i){
            $(this).remove();
        });

        $("#"+formid).prepend('<p class="ui-state-error error_p" >'+json_response.err+'</p>').hide().slideFadeToggle(300);
    }
	else{
		
	    if( typeof json_response.url != 'undefined' ){
	        //debuglog(json_response.url);
	        $.blockUI({ 
	            message: '<p style="width:220px; margin:0px auto; text-align:center;"><span style="float:left" class="ui-icon ui-icon-info"></span><span style="float:left; font-size:11px; " class="">&nbsp;&nbsp;Success! You will be redirected in 5 sec...</span><br /><img src="/images/ajax-bar-loader.gif" /></p>',
	            css:{
	                border: '5px solid #AAAAAA',
	                color:          '#000',
	                textAlign:      'center',
	                padding:        10
	            },
	            baseZ:10004,
	            timeout: 2000,
	            onUnblock: function(){
	                window.location.href = json_response.url;
	            }
	        });     
	    }
	}
}

function ShowFileInfo( fileUrl, data )
{
    var sFileName = decodeURIComponent( fileUrl.replace( /^.*[\/\\]/g, '' ) ) ;
    sFileName = sFileName.replace("http://www.humanline.com","");
	var res = $.evalJSON($.toJSON(data));
	var patt = /\d+/;
	
	var $form = $('#'+res.selectFunctionData).parents('form');
	
	//var id = patt.exec(res.selectFunctionData);

	$form.find('.previewBox' ).fadeOut(300, function(){
			$( ".thumbnailBox", $(this) ).empty().append(
		        '<div class="thumb">' +
		        '<a href="' + fileUrl + '" target="_blank" title="'+sFileName+' (' + data.fileSize + 'KB)" >'+
		        '<img src="' + fileUrl + '" alt="' + sFileName + '(' + data.fileSize + 'KB)" />' +
		        '</a>'+
		        '</div>') ;
			$form.find('.previewBox' ).slideDown(500, function(){
				var pendingPreload = [];
		        $.each( $('img',this), function(i,val){
		            pendingPreload[i] = $(val).attr('src');
		        });
				
		        $.loadImages(pendingPreload, function(){
		            $.each( $('.thumb a img', $form ), function(j,obj){
						$(obj).imageScale({maxWidth: 320, maxHeight: 320}).fadeIn(300);
		            });
		        });
			});
		    $( '#'+res.selectFunctionData ).val(fileUrl);
		});
    $(".ckfinder_dialog").dialog('close');
    $( '#'+res.selectFunctionData ).parent().parent().find( '.thumb a' ).live('click', function(){
        $(this).fancybox();
        return false;
    });

    // It is not required to return any value.
    // When false is returned, CKFinder will not close automatically.
    return false;
}


function preloadImagesFunc(elem, h, w, typsy, reposition){
		var pendingPreload = [];
        $.each( $(elem), function(i,val){
            pendingPreload[i] = $(val).attr('src');
        });
        $.loadImages(pendingPreload, function(){
            $.each( $(elem), function(i,val){
				
                $(val).imageScale({maxWidth: w, maxHeight: h}).fadeIn(300,function(){
					if(reposition){
						$(val).position({
							of:$(val).parent(),
							my:'center bottom',
							at:'center bottom',
							offset:'0 0'
						});
					}
				});
				if(typsy){
					$(val).tipsy({
						title: function(){
							return '<img src="'+$(val).attr('src')+'" />';
						},
						html:true,
						opacity:1,
						gravity:'e'
					});
				}
				
            });
        });
	}

function parseHtml( str ){
	var test = str.match(/([[#]+)(\w.[^#\"]+)([#\]]+)/g);
	//debuglog(test);
	var templabel, temp, cleared;
	if( test !== null){	
		for( var i=0; i<test.length; i++){
			templabel = test[i];
			cleared = test[i];
			cleared = cleared.replace(/([[#]+)(\w.[^\"\[#\"]+)([#\]]+)/g, "$2");
			// var labels = {...}
			if( typeof labels[cleared] != 'undefined'){
				temp = labels[cleared];
				str = str.replace( templabel, temp );
			}
			else{
				str = str.replace( templabel, cleared );
			}
		}	
	}
	else{
		//alert(test);
	}
	return str;
}







function MainHeightFixer(){
	//$("#MainContainer").css('border','1px solid red');
	var header = $("#headerContainer").height();
	var footer = $("#footerContainer").outerHeight(true);
	var scrollTop = $(window).scrollTop();
	var windowsize = $(window).height();
	var mainContainer = $("#MainContainer").outerHeight(true);
	var docheight = $(document).height();
	var newHeight = docheight-(footer+header);
	
	var pageContent = $(".pageContent").outerHeight(true);
//	debuglog( windowsize );
	
	$("#footerContainer").css({
		'position':'relative',
		'top':windowsize
	});
	//debuglog( newHeight );
	//debuglog( mainContainer );
	//$("#MainContainer").height(  );
	//debuglog(newHeight+'/'+scrollTop);	
}

function db_get_boolean(bool){
	if(parseInt(bool,10)===1){
		return 'Yes';
	}
	else{
		return 'No';
	}
}

function removeItems(array, item) {
    var i = 0;
    while (i < array.length) {
        if (array[i] == item) {
            array.splice(i, 1);
        } else {
            i++;
        }
    }
    return array;
}


function getparams(s){
    a = s.match(/[^&?=]*=[^&?=]*/g);
    r = [];
    if(a)
    {
    	for (i=0; i<a.length; i++) {
        	r[i] = '"'+a[i].match(/[^&?=]*/)[0]+'":"'+a[i].match(/=([^&?]*)/)[0].replace('=', '')+'"';
        }
    }
    return(r);
}

function redirect(){
        location.reload(true);
    }
/* obsolete
function hasEmptyFields(formData){
        for (var i = 0, ii = formData.length; i < ii; i++) {
            if(formData[i].name!='descr_architect'){
                if (!formData[i].value) {
                    return true;
                }
            }
        }
        return false;
    }

*/


var submits = 0;
function prepareForm(formname)
{
    // bind to the form's submit event
    $('#'+formname).submit(function() {
        if( submits == 0){
            //debuglog('#'+formname);
            $('input[type=submit]', this).attr('disabled', 'disabled');
            $(this).ajaxSubmit(ajaxoptions);
            submits++;
        }
        return false;
    });
}




function myFormValidate( field, mode) {
    if(mode=='valid'){
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		
        var $email = $("input[name='"+field+"']");
        var address = $email.val();
		
        if(reg.test(address) == false) {
            return false;
        }
        else
        {
            return true;
        }
    }
    else if(mode=='empty'){
        var $myfield = $("input[name='"+field+"']");
        var field_value = $myfield.val();
        if(field_value!=''){
            return true;
        }
        else{
            return false;
        }
    }
    else
    {
        return false;
    }
}




function resetQuestions(form){

    $("p[id^='question']", form).each(function(){
       if($(this).attr('id')!='question1'){
            $(this).addClass('ui-helper-hidden');
       }
    });
    
    $("[id*='ToUploadBox']", form ).each(function(){
        $(this).addClass('ui-helper-hidden');
    });
    $("p[id^='licenseUsageBox']", form).each(function(){
        $(this).addClass('ui-helper-hidden');
    });

    $("input[id*='_bool']", form).val(0);
}


function continueConfirmation(functionToCall, obj, text, title ){
    if ( typeof title == 'undefined' ) {
      title = "Confirmation of Ownership";
	}

	//create content
		var decoded = $('<div></div>').html(text);
		var content = $('<div id="confirm_dialog"></div>');
		content.html(decoded);
	
	// create dialog
	var $dialog = content.dialog({
		title: title,
		dialogClass: 'ngl_dialog_container',
		autoOpen: false,
		position: 'center',
		height: 'auto',
		width: 'auto',
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			Confirm: function() {
					functionToCall(obj);
					$(this).dialog('close');
			},
			Cancel: function() {
					$(this).dialog('close');
			}
		}
	});

	/*
	 var $dialog = $('<div id="confirm_dialog">'
                    +'<p>'
                        +'<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'
                        +text
                    +'</p>'
                    +'</div>')
    				.dialog({
			            autoOpen: false,
			            title: title,
			            height:'auto',
			            width:'250px',
			            modal:true,
			            resizable:false,
			            position:'center',
						show: 'fade',
			  			hide: 'fade',
			            buttons: {
			                Confirm: function() {
			                        functionToCall(obj);
			                        $(this).dialog('close');
			                },
			                Cancel: function() {
			                        $(this).dialog('close');
			                }
			        	}
			    	});
	*/

    $dialog.bind("dialogclose", function(){
            $(this).dialog('destroy');
            $("#confirm_dialog").remove();
    });
    $dialog.dialog('open');
}

function deleteConfirmation( functionToCall, obj ){

	//create content
		var decoded = $('<div><span>This item will be permanently deleted and cannot be recovered. Are you sure?</span></div>');
		var content = $('<div id="del_dialog"></div>');
		content.html(decoded);
	
	// create dialog
	var $dialog = content.dialog({
		title: 'Confirmation',
		dialogClass: 'ngl_dialog_container',
		autoOpen: false,
		position: 'center',
		height: 'auto',
		width: 'auto',
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			Confirm: function() {
					functionToCall(obj);
					$(this).dialog('close');
			},
			Cancel: function() {
					$(this).dialog('close');
			}
		}
	});
   
   /*
	var $dialog = $('<div id="del_dialog">'
                    +'<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be permanently deleted and cannot be recovered. Are you sure?</p>'
                    +'</div>')
    				.dialog({
			            autoOpen: false,
			            title: 'Confirmation',
			            height:'380px',
			            width:'250px',
			            modal:true,
			            resizable:false,
			            position:'center',
						show: 'fade',
						hide: 'fade',
			            buttons: {
			                'Delete': function() {
			                        functionToCall(obj);
			                        $(this).dialog('close');
			                },
			                Cancel: function() {
			                        $(this).dialog('close');
			                }
			        	}
			    	});
	*/

    $dialog.bind("dialogclose", function(){
            $(this).dialog('destroy');
            $("#del_dialog").remove();
    });
    $dialog.dialog('open');
}


function setPosition( elem, toelem ){
	$(elem).position({
        of:$(toelem),
        my: 'right top',
        at: 'right bottom',
        offset: '0 0'
    });
}

function datepicker_instance(){
    $.datepicker.setDefaults({
        showOn: 'button',
        showButtonPanel: true,
        buttonImageOnly: true,
        buttonImage: '../images/calendar.gif',
        yearRange: '1980:2050',
        dateFormat: 'd MM, yy',
        changeYear: true
    });
}


function myframe_loaded(){
	$('iframe').css('height', $('iframe').contents().find(".tablehead").parent().height()+350);
}

//$.extend({
//    changeTab : function () {
//		// The "tab widgets" to handle
//		var tabs = $('.ui-tabs');
//		var hash = window.location.hash;
//	
//		// This selector will be reused when selecting actual tab widget A elements.
//		var tab_a_selector = 'ul.ui-tabs-nav li a';
//		$(window).bind( 'hashchange', function(e) {
//			var hash = window.location.hash;
//			//console.log(hash);
//			tabs.find("ul.ui-tabs-nav li a[href='"+hash+"']").parent().removeClass('ui-state-disabled');  
//			tabs.find("ul.ui-tabs-nav li a[href='"+hash+"']").trigger( 'click' );  
//			
//			//$.scrollTo( '#columns2standart',300);
//			//$('html, body').animate({ scrollTop: $("#").offset().top() }, 300);  
//		});
//		
//		// Since the event is only triggered when the hash changes, we need to trigger
//		// the event now, to handle the hash the page may have loaded with.
//		if(hash.length != 0 && tabs.find("ul.ui-tabs-nav li a[href='"+hash+"']").length != 0){	
//		  	$(window).trigger( 'hashchange' );
//		} 
//    }
//});
	


$(window).load(function() {
	
	// login dialog
    $(".login-button" ).bind('click', function(e) {

//    	e.preventDefault();
//        
//    	console.log($(this).attr('href'));
//    	
//        var send = {
//    		'ajax': "2",
//    		'showhtml': "2"
//        }
//        var url = $(this).attr('href');
//            
//        var encoded = $.toJSON(send);
//        var params = $.evalJSON(encoded);
//        	
//    	$.post(url, params, function(response) {
//    	});
    	
    });
    
        
        
//        		var $this = $(this);
//        if( $(".loginBoxBuy").length != 0){
//			$(this).remove();
//			$(".loginBoxBuy").slideFadeToggle(300, function(){
//                $(this).remove();
//            });
//		}
		
//        if( $(".loginBox").length == 0 ){
//            var send = new Object();
//            send.ajax = "2";
//            send.showhtml = "2";
//            var url = $(this).attr('href');
//
//            var encoded = $.toJSON(send);
//            var params = $.evalJSON(encoded);
//            //debuglog(encoded);
//            $.post(url,params,function(response){
//                
        		//alert(1);
//                var $loginBox = $('<div class="loginBox ui-widget ui-widget-content ui-corner-bottom"></div>');
//                $loginBox.hide();
//                $loginBox.append(response);
//               
//				$('body').append($loginBox);
//	            setPosition($loginBox, $this);
//				
//				$(".liveCheckbox").checkbox();
//                
//				$this.find('.ui-icon').removeClass('ui-icon-circle-triangle-s').addClass('ui-icon-circle-triangle-n');
//                $this.animate({'background-color':'#aaaaaa'},300);
//
//                $loginBox.find("p.error_p").each(function(i){
//                            $(this).remove();
//                        });
//                $loginBox.slideFadeToggle(300);
//                $("input[name='ajax']").val('2');
//				
//				
//				$("#btnLoginSubmit").live('click',function(ev){
//					ev.preventDefault();
//					var $form = $("#loginForm");
//					var $overlay = $('<div class="loading-overlay ui-corner-bottom" ></div>');
//					$('body').append($overlay);
//                    var $parent = $form.parent().parent();
//                    $overlay.height($parent.height()+22);
//                    $overlay.width($parent.width()+22);
//                    $overlay.position({
//                        of:$loginBox,
//                        my: 'right top',
//                        at: 'right top',
//                        offset: '0 0'
//                    });
//                    
//                    $overlay.css({
//                        "background-color":"#000",
//                        "background-image":"url(/images/login_loading.gif)",
//                        "background-position":"center center",
//                        "background-repeat":"no-repeat",
//                        "z-index":10002,
//                        "opacity":"0"
//                    })
//					.animate({
//                        opacity: 0.6
//                    },300);
//					
//                    var loginoptions = {
//						beforeSubmit: loginShowRequest,
//						success: loginShowResponse,
//						dataType:'json'
//					}
//                    $("#loginForm").ajaxSubmit(loginoptions);
//				});
//
//            });
//        }
//        else{
//            $this.find('.ui-icon').removeClass('ui-icon-circle-triangle-n').addClass('ui-icon-circle-triangle-s');
//            $this.animate({'background-color':'#bf0021'},300, function(){
//                $(this).removeAttr('style');
//            });
//            $(".loginBox").slideFadeToggle(300, function(){
//                $(this).remove();
//            });
//        }
//
//        return false;
//    });
	
	
	
	//initial check for existing hash and call method for selecting the Tab
    //$.changeTab();

    /*
    var tg1 = $("#timeLine").timeline({
                    "min_zoom":5, 
                    "max_zoom":100, 
                    "show_centerline":true,
                    "data_source":"/en/calendar.html?ajax=2&action=timeline",
                    //"data_source":"#humanline-table",
                    "icon_folder":"/images/timeglider/",
                    "show_footer":true,
                    "size_importance":true,
                    "display_zoom_level":true
            });
    */
    
	$('iframe').css('height', $('iframe').contents().find(".tablehead").parent().height()+350);

	//$('body').css({opacity:1},3000);
	// THEME SWITCHER
	if ($.fn.themeswitcher) {
		$('#switcher').themeswitcher();
	} else {
		$('#switcher').html("")
	}
	
	//MainHeightFixer();
	
	$('.read-more > a, .re-collapse > a').live('mouseenter mouseleave',function(event){
		if( event.type=='mouseenter'){
			$(this).removeClass('ui-state-default').addClass('ui-state-hover');
		}
		if( event.type=='mouseleave'){
			$(this).removeClass('ui-state-hover').addClass('ui-state-default');
		}
	});
	
	$("#imagesBox .ui-datepicker-prev, #lightboxBox .ui-datepicker-prev").live('click',function(e){
		e.preventDefault();
		$(this).parent().parent().find('.ui-datepicker-calendar').slideFadeToggle(300);
		if( $(this).find('span.ui-icon').hasClass('ui-icon-triangle-1-s') ){
			$(this).find('span.ui-icon').removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e');
		}
		else{
			$(this).find('span.ui-icon').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
		}
		
	});
	
	
	
//	$("a.lightbox").livequery(function(){
//		/*$(this).tipsy({
//			gravity: 's',
//			fade: true,
//			title: function() { 
//				return this.getAttribute('title'); 
//			}
//		});*/
//		$(this).imagePreviewNew();
//	});
	
	$(".ImageLBBigBlock .smallButtons a").livequery(function(){	
		$(this).tipsy({
			gravity: 'sw' ,
			fade: true
		});
	});
	
    // GLOBAL RULES
    if($.ui){
        $.datepicker.setDefaults({
            showOn: 'button',
            showButtonPanel: true,
            buttonImageOnly: true,
            buttonImage: '../images/calendar.gif',
            yearRange: '2010:2050',
            dateFormat: 'd MM, yy',
            changeYear: true
        });
    }
    else{
        setTimeout( "datepicker_instance()",1000 );
    }
	
	
	
	/*
	$("input[name='ajax']").livequery(function(){
		$(this).val(2);
	});
	*/
    $("input[name='showhtml']").livequery(function(){
		$(this).val(2);
	});
	
	$("table.grid").livequery(function(){
		$( "table.grid tr:odd" ).addClass('odd');
	});

//    $(".inboxWidget span:not(.ui-icon)").checkInbox(
//       //{interval:5000}
//    );
    
//	$('#subscribeSubmit').bind('click',function(ev){
//		ev.preventDefault();
//		
//		$('#subscribeForm').ajaxSubmit(ajaxoptions);
//		
//		
//	});
	
	
	
	   	  
	/*
	$("#BuyNotLogged").bind('click', function(e){
		
		e.preventDefault();
		var $this = $(this);
		
		if( $(".loginBox").length != 0){
			$("a[title='Login']" ).trigger('click');
		}

		if( $(".loginBoxBuy").length == 0 ){
            var send = new Object();
            send.ajax = "2";
            send.showhtml = "2";
            var url = $(this).attr('href');
            var encoded = $.toJSON(send);
            var params = $.evalJSON(encoded);
            $.post(url, params, function(response){
            	//debuglog(response);
               
                var $loginBox = $('<div class="loginBoxBuy ui-widget"></div>');
                $loginBox.hide();
                $loginBox.append(response);
               
				$loginBox.css({'position':'none'});
				$("#BuyNotLogged").parent().append($loginBox);
				$(".liveCheckbox").checkbox();
                
                $loginBox.find("p.error_p").each(function(i){
                            $(this).remove();
                        });
                $loginBox.slideFadeToggle(300);
                $("input[name='ajax']").val('2');

                $("#btnLoginSubmit").live('click',function(ev){
					ev.preventDefault();
					var $form = $("#loginForm");
					var $overlay = $('<div class="loading-overlay ui-corner-bottom" ></div>');
					$('body').append($overlay);
                    var $parent = $form.parent().parent();
                    $overlay.height($parent.height()+22);
                    $overlay.width($parent.width()+22);
                    $overlay.position({
                        of:$loginBox,
                        my: 'right top',
                        at: 'right top',
                        offset: '0 0'
                    });
                    
                    $overlay.css({
                        "background-color":"#000",
                        "background-image":"url(/images/login_loading.gif)",
                        "background-position":"center center",
                        "background-repeat":"no-repeat",
                        "z-index":10002,
                        "opacity":"0"
                    })
					.animate({
                        opacity: 0.6
                    },300);
					
                    var loginoptions = {
						beforeSubmit: loginShowRequest,
						success: loginShowResponse,
						dataType:'json'
					}
                    $("#loginForm").ajaxSubmit(loginoptions);
				});

            });
        }
        else{
            
            $(".loginBoxBuy").slideFadeToggle(300, function(){
                $(this).remove();
            });
        }
		
	});
	*/
	$(".ui-icon-refresh").hover(
		function(){
			$(this).css('cursor','pointer');
			$(this).css('background-image','url(/css/base/images/ui-icons_cd0a0a_256x240.png)');
			$(this).css('background-position','-64px -80px');
		},
		function(){
			$(this).css('cursor','none');
			$(this).css('background-image','url(/css/base/images/ui-icons_222222_256x240.png)');
			$(this).css('background-position','-64px -80px');
		} 	
	);
	
	$("#refresh_forgot").click(function(ev){
		ev.preventDefault();
		$("#human_code").val('').removeClass('invalid');
		//$("span:contains(' sum ')").remove();
		var filename = '/check.php?'+$.randomBetween(1000, 9999);
		var myparams = '"regen_code":"1"';
		var $newimage = '';
		var params = $.evalJSON('{'+myparams+'}');
		
		$.ajax({
			'url': filename,
			'type': "POST",
			'async': false,
			'data': params,
			'success': function(returned_data){
				
				$("#human_code_image").fadeOut(1000, function(){
					$(this).attr('src', '').attr('src', '/genCode.php?file=' + Math.floor(Math.random() * 10001)).fadeIn(1000, function(){
					
					});
				});
			}
		});
				
	});
	
	$("#refresh_register").click(function(ev){
		ev.preventDefault();
		$("#human_code").val('').removeClass('invalid');
		//$("span:contains(' sum ')").remove();
		var filename = '/check.php?'+$.randomBetween(1000, 9999);
		var myparams = '"regen_code":"1"';
		var $newimage = '';
		var params = $.evalJSON('{'+myparams+'}');
		
		$.ajax({
			'url': filename,
			'type': "POST",
			'async': false,
			'data': params,
			'success': function(returned_data){
				
				$("#human_code_image").fadeOut(1000, function(){
					$(this).attr('src', '').attr('src', '/genCode.php?file=' + Math.floor(Math.random() * 10001)).fadeIn(1000, function(){
					
					});
				});
			}
		});
				
	});
	
    //SEARCH FORM
	//Cufon('#searchFormContainer .searchButton', {fontFamily: 'trajanpro-bold'});
    if( $("#searchFormContainer").length !=0 ){
		$("#searchFormContainer").find('form').find('.ui-checkbox').addClass('left');
	}
	$('button.searchButton').live('click',function(){
       $(this).parent().submit(function(){
            $('input[type=submit]', this).attr('disabled', 'disabled');
       });
    });
    
    $('button.searchButton').hover(
        function(){$(this).css('cursor','pointer');},
        function(){$(this).css('cursor','normal');}
    );
	
    //$('#searchFormContainer div.searchFieldContainer').addClass('rounded-r10');
    //$('#searchFormContainer div.searchButtonContainer').addClass('rounded-r10');
        
	/*$(".treeview").livequery(function(){
	    $(".treeview > li").css({
	        'padding-left':'0'
	    });
		//$(".treeview > li > span").addClass('ui-state-default');
	    $(".treeview > li > span").css({
	        'width':'190px'
	    });
	    //$('.treeViewBlock > h2').addClass('rounded-r10-top');

		
	});*/
	
	//$('.treeViewBlock').addClass('ui-expanded');
	//$('.treeViewBlock > h2').append('<span class="ui-icon-white ui-icon-minus ui-expand-button"></span>')
	/*$('.ui-expand-button').livequery(function(){
		$(this).css({
			'position':'relative',
			'top':'-20px',
			'left':'179px'
		})
	});*/
		
	$('.treeViewBlock > h2').bind('click', function(e){
		e.preventDefault();
		$(this).parent().find('ul.treeview').slideToggle(300);
		$(this).parent().find('ul.menutreeview').slideToggle(300);
		if($(this).parent().hasClass('ui-expanded')){
			//$(this).addClass('ui-icon-white');
			$(this).parent().removeClass('ui-expanded');
			$(this).find('.ui-icon-white').removeClass('ui-icon-minus').addClass('ui-icon-plus');
		}
		else{
			//$(this).addClass('ui-icon-white');
			$(this).parent().addClass('ui-expanded');
			$(this).find('.ui-icon-white').removeClass('ui-icon-plus').addClass('ui-icon-minus');
		}
		
		return false;
	});
	
	$('.treeViewBlock > h2').hover(
		function(){ $(this).css('cursor','pointer'); },
		function(){ $(this).css('cursor','normal');}
	);
		
		
		
	
	
    //$('.treeViewBlock .treeViewFooter').addClass('rounded-r10-bottom');
	/*
    $('ul#black span').hover(
       function(){$(this).css('border-bottom','1px dashed #dfdfdf');},
       function(){$(this).css('border-bottom','1px solid #ffffff');}
    );
	*/
	
    //TOP MENU BUTTONS CORNERS
    //$('#header .plain-menu ul li a').addClass('rounded-r10-bottom');


    // NEWSBOX ON HOME PAGE
    if($("#newsBox ul").length!=0){
        $('.news_content').hover(
            function(){$(this).parent().addClass('news_content_hover');},
            function(){$(this).parent().removeClass('news_content_hover');}
        );
        
        
        $('#newsBox ul li:last').css('border','none');
    }
	
    $( '.previewBox a' ).livequery(function(){
        $(this).fancybox();
    });
	
	$(".calendar").livequery(function(){
		$(this).datepicker();
	});
	$(".ui-datepicker-trigger").livequery(function(){
		$(this).addClass('right');
	});
		
	/*
	// ********** RF ORDER ORDER ********** //
	if( $("#orderForm").length != 0 ){
		
		$("[id^='ordersize']:radio").each(function(i, obj){
			
			// get row
			var $row = $(obj).parent().parent();
			
			// get button
			var $button = $(obj).next('.ui-button');
			
			$button.bind('click',function(){
				
				var id = $(obj).attr('id');
				
				var request = new Object();
				request.ajax = 2;
				request.action = 'start-order';
				request.size_id = $('#'+id).val();
				request.image_id = $("[name='image_id']").val();
				var encoded = $.toJSON(request);
				var params = $.evalJSON(encoded);
				var url = "/"+labels['lang']+'/orderprocess.html';
				$.ajax({
					'data' : params,
					'url' : url,
					'type':"POST",
					'async' : false,
					'dataType':'json',
					'success':function(json){
						$(json).each(function(i,obj){
							if( obj.size_id == request.size_id ){
								
								//$("#image_calc_price").val( obj.calculated_price );
								//$("#selected_price").html(obj.calculated_price+'&#36;');
								
								var save_request = {
									'action': 'save-state1',
									'image_id': obj.image_id,
									'custom_data': obj.calculated_w+'|'+obj.calculated_h,
									'calculated_price': obj.calculated_price,
									'ajax': 2
								}
								
								var encoded_save = $.toJSON(save_request);
								var params_save = $.evalJSON(encoded_save);
								
								$.ajax({
									'type':"POST",
									'url' : url,
									'dataType':'json',
									'data' : params_save,
									'async' : false,
									'success': function(json){
									if (typeof json.err != 'undefined' && json.err.length != 0) {
										show_stack_bottomleft(true, json.err);
									}
									else {
										if (typeof json.msg != 'undefined' && json.msg.length != 0) {
											show_stack_bottomleft(false, json.msg);
										}
										
										if( typeof json.data.order_id != 'undefined'){
											$("#order_id").val( json.data.order_id );
										}
									}
								}
								});
								
								return false;
							}
						});
					}
				});
				
				$(this).parents('tbody').find('tr').each(function(i,obj){
					$(obj).removeClass('selected-row');
				});
				
				$(this).parent().parent().addClass('selected-row');
			
			});	
						
			if( i == $("[id^='ordersize']:radio").length-1 ){
				$button.trigger('click');
			}
			
		});
		
	}
	
	
	if($("#orderImageForm").length != 0){
		$("#orderImageForm").validate({
			rules:{
				os0:{
					required:true
				},
				os1:{
					required:true
				},
				os2:{
					required:true
				},
				os3:{
					required:true
				},
				os4:{
					required:true
				},
				os5: {
					required: true,
					latinletterssonly: true,
					minlength: 2
				},
				os6: {
					required: true,
					latinletterssonly: true,
					minlength: 2
				},
				os7: {
					required: true,
					latinletterssonly: true,
					minlength: 2
				},
				os8: {
					required: true,
					address:true
				},
				os9: {
					required:true,
					city:true
				},
				os10: {
					required: true,
					postalcode: true
				},
				os11: {
					selectedoption: true,
					digits: true
				}
			},
			messages:{
				os0:{
					required: "Missing data"
				},
				os1:{
					required: "Missing data"
				},
				os2:{
					required: "Missing data"
				},
				os3:{
					required: "Missing data"
				},
				os4:{
					required: "Missing data"
				},
				os5: {
					required: "Please enter your first name",
					latinletterssonly: "Please enter only latin letters here",
					minlength: "Your First name is too short"
				},
				os6: {
					required: "Please enter your last name",
					latinletterssonly: "Please enter only latin letters here",
					minlength: "Your Last name is too short"
				},
				os7: {
					required: "Please enter your business name",
					latinletterssonly: "Please enter only latin letters here",
					minlength: "Your business name is too short"
				},
				os8: {
					required: "Please enter your address",
					address: "Please enter your address"
				},
				os9: {
					required: "Please enter your city"
				},
				os10: {
					required: "Please enter your postal code"
				},
				os11: {
					selectedoption: "Please choose a country",
					digits: "Unsupported format"
				}
			},
			submitHandler: function(form) {
                form.submit();
            },
            onfocusout: false,
            onkeyup: false,
            onkeypress: false,
            onsubmit: true,
            success: "",
            errorClass: "invalid",
            errorElement: "em",
            errorPlacement: function(error, element) {
                //debuglog($("label[for*='"+element.attr('name')+"']").get(0));
                var label = $("label[for*='"+element.attr('name')+"']").get(0);

                $(label).append(error);
            },
            debug:false
		});
	}

    */
/* to rethink - it should return an array with the disabled tabs
    var disabledTabs = function(){
            var index_to_disable = new Array();
            var selectedTab;
            if( $.cookie('uploadsSteps') != null && $.cookie('uploadsSteps') != '' ){
                selectedTab =  $.cookie('uploadsSteps');
            }else{
                selectedTab = 0;
            }
            for(var i=0;i<5;i++){
                if(i != selectedTab){
                    index_to_disable.push(i);
                }
            }
           
            return index_to_disable;
        };
    */
	
	
//	
//    $("input[type='file']").hover(
//        function(){
//            $(this).parent().find('input.ui-state-default').each(function(){
//                $(this).addClass('ui-state-hover');
//            });
//        },
//        function(){$(this).parent().find('input.ui-state-default').each(function(){
//                $(this).removeClass('ui-state-hover');
//            });
//        }
//    );

    
	

    //$('#file_release').hideuploadfile();
    
    /*
    $('#resetForm3').live('click',function(){
        //debuglog($(this).attr('id'));
        $("input[name*='_radio']").each(function(){
            $(this).attr('checked',false);
            //debuglog($(this).attr('id'));
        });
        $("[id^='radioset']").buttonset("refresh");
        
        
        resetQuestions( $("p[id^='question']") );
        return false;
    });
    */

	

    $("a.openImageInDialog").live('click', function(){
        $("#internalPage").dialog("destroy");
        $("#internalPage").remove();
        var url = String($(this).attr('href').split("?",1));
        var myparams = getparams(url);
        //debuglog(myparams);
        /*if(myparams.length > 0){
            myparams += ','
        }*/
        //myparams += '"ajax":"2"';
        var params = $.evalJSON('{'+myparams+'}');
		params.ajax = 2;
        var $dialog = $('<div id="internalPage"></div>');
        $dialog.dialog({
            autoOpen: false,
            title: $(this).attr('title'),
            width:800,
            height:600,
            minHeight:600,
            modal:true,
            resizable:true,
            position:'center',
            open: function(){
                
                    $("#internalPage").append('<img src="'+url+'" />');
                

               

            }
        });
        $("#internalPage").bind("dialogclose", function(){
            $("#internalPage").dialog('destroy');
            $("#internalPage").remove();
        });
        $dialog.dialog('open');
        
    });
    $("a.openInDialog").live('click', function(){
        $("#internalPage").dialog("destroy");
        $("#internalPage").remove();
        var url = String($(this).attr('href').split("?",1));
        var myparams = getparams(url);
        //debuglog(myparams);
        /*if(myparams.length > 0){
            myparams += ','
        }*/
        //myparams += '"ajax":"2"';
        var params = $.evalJSON('{'+myparams+'}');
		params.ajax = 2;
		
        var $dialog = $('<div id="internalPage"></div>');
        $dialog.dialog({
            autoOpen: false,
            title: $(this).attr('title'),
            width:800,
            height:600,
            minHeight:600,
            modal:true,
            resizable:true,
            position:'center',
            open: function(){
                $.get(url, params, function(data){
                    $("#internalPage").append(data);
                });

                

            }
        });
        $dialog.bind("dialogclose", function(){
            $(this).dialog('destroy');
            $("#internalPage").remove();
        });
        $dialog.dialog('open');
        return false;
    });

	// uploads datatables are loaded in the uploads.php
   
	// START GROUP BUTTONS
    $('.clearField').live('click',function(){
        $(this).parent().find("input[type='text']").val('');
        $(this).parent().find('.thumbnailBox' ).html('');
        $(this).parent().find('.previewBox').hide();
        return false;
    });
    $('.clearFieldNewsletter').live('click',function(){
        $(this).parents('table').find("input[type='text']").val('');
        $(this).parents('table').find('.thumbnailBox' ).html('');
        $(this).parents('table').find('.previewBox').hide();
        return false;
    });

    $(".selectFile").live('click', function(){
        var returnField = $(this).parents('form').find("input[name*='_picture']").attr('id');
        //debuglog(returnField);
        var $dialog = $('<div class="ckfinder_dialog"></div>')
        .dialog({
            autoOpen: false,
            title: 'File Manager',
            width:650,
            height:420,
            minHeight:420,
            modal:true,
            resizable:true,
            position:'center',
			show: 'fade',
  			hide: 'fade',
            open: function(){
				var finder = new CKFinder() ;
				// The path for the installation of CKFinder (default = "/ckfinder/").
                finder.BasePath = '/ckfinder/' ;	
                finder.SelectFunction = ShowFileInfo;
                finder.SelectFunctionData = returnField;
                $(".ckfinder_dialog").append('<h3 class="grey">Doubleclick to select a file</h3>')
                $(".ckfinder_dialog").append(finder.CreateHtml());
                $('.CKFinderFrame').attr('width','610').attr('height','328');
               

            }
        });
        $dialog.bind("dialogclose", function(){
            $(".ckfinder_dialog").dialog('destroy');
            $(".ckfinder_dialog").remove();
        });
        $dialog.dialog('open');
		return false;
    });
	
	//END GROUP BUTTONS
    
	
	
	
	
	
    $("#recaptcha-refresh").bind('click', function(e){
        $("#recaptcha_image").animate({
            opacity:0
        },500, function(){
            $(this).empty();
            Recaptcha.reload();
            
            $(this).delay(500).animate({
                opacity:1
            },500);
            
        });
    });
	
if( $("#forgot_password").length!=0 ){
	    $("#forgot_password").validate({
	        rules: {
	            user_email:{
	                required:true,
	                email: true,
	                remote:{
	                    url: "/check.php",
	                    type: "post",
	                    data: {
	                        email: function() {
	                            return $("#user_email").val();
	                        },
	                        fieldname: "email",
	                        target:'email',
	                        validate: '1'
	                    }
	                }
	            }
	            
	        },
	        messages: {
	            user_email: {
	                required:"Email field is empty",
	                email:"Provided email is invalid",
	                remote:"There is no such registered email"
	            }
	        },
	        submitHandler: function(form) {
	            form.submit();
	            //debuglog('form.serialize()');
	        },
	        onfocusout: false,
	        onkeyup: false,
	        onsubmit: true,
	        success: "",
	        errorClass: "invalid",
	        errorElement: "em",
	        errorPlacement: function(error, element) {
	            var label = $("label[for='"+element.attr('name')+"']").get(0);
	            
	            $(label).append(error);
	        },
	        debug:false
	    });
	    
	
}
   
	
    //$("div.ItemThumb a[class^='authorized']").fancybox();
	
    $(".MainContainer .gradientBack .SearchBox fieldset input[type='submit']").css('float','right');
	
    $(".login-box input[type!='submit']").focus(function(){
        $(this).css('background-color','#FFFFC6');
    });
	
	
    $(".login-box input[type!='submit']").blur(function(){
        $(this).css('background-color','#fff');
    });
	
/*
    $("#BuildingsInfo table tr td a").hover(
        function(){
            $(this).css('cursor','pointer');
            $(this).css('text-decoration','underline');
        },
        function(){
            $(this).css('text-decoration', 'none');
        }
        );
   */ 
$("#close_blockui").live('click', function(){
    $.unblockUI();
    return false;
});
	
$("#close_blockui").livequery(function(){
    $(this).hover(
        function(){
            $(this).css('cursor','pointer').addClass('ui-state-hover');
        },
        function(){
            $(this).css('cursor','none').removeClass('ui-state-hover');
        }
    );
});

$("div#dialog-warning").dialog({
    bgiframe: true,
    modal: true,
    autoOpen: true,
    resizable: false,
    buttons: {
        Ok: function() {
            $(this).dialog('close');
            //$(this).dialog('destroy');
            history.back();
        }
    }
});

	
$("#forgot_password input").bind('click', function(e){
    $("span."+$(this).attr('id')+"_err").remove();
});
/*
$("input[type='text']").livequery(function(){
			$(this).placeholder();
		});
	*/	
//console.profileEnd();
});
