Notifier = function(){
	var span = document.createElement("SPAN");
	var div = document.createElement("DIV");
	div.id = "notifier_box";
	span.appendChild(div);
	document.body.appendChild(span);
	this.msgBox = div;
}

Notifier.prototype.scrollHandler = function () {
	this.msgBox.style.top = this.getScrollTop();
}

Notifier.prototype.display = function ( str ) { 
	this.msgBox.style.display = 'block'; 
	this.msgBox.style.visibility = 'visible';
	if ( this.msgBox.currentStyle && this.msgBox.currentStyle.position == 'absolute' ) {
		this.msgBox.style.top = getWindowScrollTop();
		window.notifier = this;
		window.onscroll = function() {
			this.notifier.msgBox.style.top = getWindowScrollTop();
		};
	};
	this.msgBox.innerHTML = str;
}

Notifier.prototype.hide = function () {
	this.msgBox.style.display = 'none';
	this.msgBox.style.visibility = 'hidden';
	window.onscroll = null;
}

function getWindowScrollTop() {
	if ( document.documentElement.scrollTop )
		return document.documentElement.scrollTop;
	return document.body.scrollTop;
}

function show_contacts() {
	document.write('<b>Контакты</b><br/><br/>по вопросам работы сайта:<br>тел. (044) 383-13-81<br/><a href="mailto:info@saletime.biz" rel="nofollow">info@saletime.biz</a><br/><br/>по вопросам размещения товаров:<br>тел. (044) 383-13-82<br/><a href="mailto:manager@saletime.biz" rel="nofollow">manager@saletime.biz</a>');
}


function ajax(url, method, params, before, success, error) {
	options = {
		url:url,
		method:method
	}
	if (params != undefined && params != '') options['data'] = params
	if (before != undefined && before != '') options['beforeSend'] = before;
	if (success != undefined && success != '') options['success'] = success;
	if (error != undefined && error != '') options['error'] = error;
	$.ajax(options)
}

function AddFavorite() {
	url = location.href;
	title = document.title;
	if((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)){
		window.external.AddFavorite(url,title);
	}
	else{
		alert("Нажмите CTRL-D (Netscape, Mozilla) или CTRL-T (Opera)");
	}
}


function successaddquick(msg) {
	var data = eval('('+msg+')');
	if (data.error != '') {
		$('#message_registration_box').html('');
		$('#message_registration_box').html(data.error+'<br/><br/>');
	} else {
		$('#message_registration_box').html('');
		$('#message_registration_box').html(data.message+'<br/><br/>');
		$('#email_registration_box').val('');
	}
}

function successlogin(msg) {
	var data = eval('('+msg+')');
	if (data.error != '') {
		$('#message_login').html('');
		$('#error_login').html(data.error);
	} else {
		ajax('{/literal}{$SITE_ROOT}{literal}?controller=user&action=usermenu&ajax=true', 'GET', '', before, successusermenu);
		$('#error_login').html('');
		$('#message_login').html(data.message);
	}
}

function successusermenu(msg) {
	$('#login').after(msg);
	$('#login').remove();
	$('#quickregistration').remove();
}

function change_captcha_reg_form(SITE_ROOT) {
	var path = SITE_ROOT+'libs/captcha/captchasecurityimages.php?width=120&height=45&characters=5&test='+rand(1, 100);
	$("#captcha_reg_form").attr('src', path);
	return false;
}

function showhideremember() {
	$('#remember').show();
}

function checkall_messages(status) {
	$('#messages').find("input:checkbox").each(function() {
			$(this).attr("checked", status);
	});
}

function checkall_editphotos(status) {
	$('#photos').find("input:checkbox").each(function() {
			$(this).attr("checked", status);
	});
}


function change_captcha_captcha_addquick(SITE_ROOT) {
	var path = SITE_ROOT+'libs/captcha/captchasecurityimages.php?type=gb&test='+rand(1, 100);
	$("#captcha_addquick").attr('src', path);
	return false;
}

function checknick(SITE_ROOT) {
	var nik = Base64.encode($('#nik').val());
	if (nik != '') ajax(SITE_ROOT+'?controller=user&action=checknick&ajax=true&nik='+nik, 'GET', '', before, successchecknick);
	return false;
}

function successchecknick(msg) {
	var data = eval('('+msg+')');
	if (data.error != '') {
		$('#message_nik').html('&ndash; &nbsp;'+data.error);
	} else {
		$('#message_nik').html('&ndash; &nbsp;'+data.message);
	}	
}

function hideandshow(className, show_id, hide_id) {
	$('#login_registration').removeAttr('class');
	$('#login_registration').attr('class', className);
	$('#'+hide_id).hide();
	$('#'+show_id).show();
}

function sale_show(className1, className2, show_id, hide_id) {
	$('#left_side_sale').removeAttr('class');
	$('#left_side_sale').attr('class', className1);
	$('#right_side_sale').removeAttr('class');
	$('#right_side_sale').attr('class', className2);
	
	$('#'+show_id).show();
	$('#'+hide_id).hide();
}

function hideandshowgoods(className1, className2, show_id, hide_id) {
	$('#goods_left').removeAttr('class');
	$('#goods_left').attr('class', className1);
	$('#goods_right').removeAttr('class');
	$('#goods_right').attr('class', className2);
	
	$('#'+show_id).show();
	$('#'+hide_id).hide();
}

function message_show(id1, id2, show_id, hide_id) {
	$('#'+id1).removeAttr('class');
	$('#'+id1).attr('class', 'stock-list-left-active');
	$('#'+id2).removeAttr('class');
	$('#'+id2).attr('class', 'stock-list-left');
	
	$('#'+show_id).show();
	$('#'+hide_id).hide();
}

function profile_steps(className1, className2, show_id, hide_id) {
	$('#left_side_profile').removeAttr('class');
	$('#left_side_profile').attr('class', className1);
	$('#right_side_profile').removeAttr('class');
	$('#right_side_profile').attr('class', className2);
	
	$('#'+show_id).show();
	$('#'+hide_id).hide();
}

function salesbymail(className, value) {
	$('#subscription_unsubscription').removeAttr('class');
	$('#subscription_unsubscription').attr('class', className);
	$('#type_subscription').val(value);
	return false;
}

function goodsforshops(url) {
	ajax(url, 'GET', '', before, success_goodsforshops);
}

function sale_comment(url) {
	ajax(url, 'GET', '', before, success_sale_comment);
}

function imageforshops(url) {
	ajax(url, 'GET', '', before, success_imageforshops);
}

function index_sales(page, SITE_ROOT, sortby) {
	ajax(SITE_ROOT+'?controller=sale&action=getajaxsales&ajax=true&currentPage='+page+'&sale_sortby='+sortby, 'GET', '', before, success_index_sales);
}

function changeleftchannel(SITE_ROOT, id) {
	ajax(SITE_ROOT+'?controller=channel&action=getchannels&ajax=true&id='+id, 'GET', '', before, success_changeleftchannel);
}

function userimages(url) {
	ajax(url, 'GET', '', before, success_userimages);
}

function userimages_view(url) {
	ajax(url, 'GET', '', before, success_userimages_view);
}

function view_shop_currentsales(page, SITE_ROOT, intShopID) {
	ajax(SITE_ROOT+'?controller=sale&action=currentsaleforshop&ajax=true&currentPage='+page+'&intShopID='+intShopID, 'GET', '', before, success_view_shop_currentsales);
}

function view_shop_archivesales(page, SITE_ROOT, intShopID) {
	ajax(SITE_ROOT+'?controller=sale&action=archivesaleforshop&ajax=true&currentPage='+page+'&intShopID='+intShopID, 'GET', '', before, success_view_shop_archivesales);
}

function index_shops(page, SITE_ROOT, sortby) {
	ajax(SITE_ROOT+'?controller=shop&action=getajaxshops&ajax=true&currentPage='+page+'&shop_sortby='+sortby, 'GET', '', before, success_index_shops);
}

function getajaxsaleshops_shops(page, SITE_ROOT, intSaleID) {
	ajax(SITE_ROOT+'?controller=shop&action=getajaxsaleshops&ajax=true&intSaleID='+intSaleID+'&currentPage='+page, 'GET', '', before, success_getajaxsaleshops_shops);
}

function getajaxshopforcard_shops(page, SITE_ROOT, intCardID) {
	ajax(SITE_ROOT+'?controller=shop&action=shopforcard&ajax=true&intCardID='+intCardID+'&currentPage='+page, 'GET', '', before, success_shopforcard_card);
}

function success_view_shop_currentsales(msg) {
	$('#current_sales').html(msg);
	activateRatings('salecurrent_ratingSpan');
}

function success_lastgoods(msg) {
	$('#lastgoods').html(msg);
	activateRatings('goodsforshop_ratingSpan');
}

function success_shopforcard_card(msg) {
	$('#shops').html(msg);
	activateRatings('shop_ratingSpan');
}

function successleftgoods(msg) {
	$('#shop_goods_right').html(msg);
	activateRatings('goodsleftforshop_ratingSpan');
}

function successrightcontacts(msg) {
	$('#login-block-container').html(msg);
}

function success_changeleftchannel(msg) {
	$('#channel').html(msg);
}

function success_view_shop_archivesales(msg) {
	$('#archive_sales').html(msg);
	activateRatings('salearchive_ratingSpan');
}

function success_goodsforshops(msg) {
	$('#goodsforshop').html(msg);
	activateRatings('goodsforshop_ratingSpan');
}

function success_getajaxsaleshops_shops(msg) {
	$('#shops').html(msg);
	activateRatings('shop_ratingSpan');
}

function successtopminisites(msg) {
	$('#topminisites').html(msg);
}

function success_sale_comment(msg) {
	$('#comments').html(msg);
}

function success_index_sales(msg) {
	$('#sales').html(msg);
	 activateRatings('sale_ratingSpan');
}

function success_imageforshops(msg) {
	$('#images').html(msg);
	 $('#photogalery a').lightBox();
}

function success_userimages(msg) {
	$('#userimages').html(msg);
}

function successrightpart(msg) {
	$('#right-sidebar').html(msg);
}

function success_userimages_view(msg) {
	$('#userimages').html(msg);
	$('#images_list a').lightBox();
}


function activateRatings(classname){
	$("."+classname).not(".activated").each(function(){
			new Rating(this.id);
		}).addClass(".activated");
	}

function success_index_shops(msg) {
	$('#shops').html(msg);
	 activateRatings('shop_ratingSpan');
}

function Rating(div_id){
	this.div = document.getElementById(div_id);
	this.rating = this.div.getAttribute("rating");
	this.intId = this.div.getAttribute("intId");
	this.enabled = this.div.getAttribute("enabled") == "1" ? true : false ;
	this.imgPath = this.div.getAttribute("imgPath");
	this.file = this.div.getAttribute("file");
	this.controller = this.div.getAttribute("controller");
	if (notifier) this.notifier = notifier;

	this.stars = new Array();
	this.starTypes = new Array();

	this.createStars();
};


Rating.prototype.recalculateStars = function (rating){
	if (rating > 5) {
		rating = 5;
	}
	var roundRating = Math.round(rating * 2) / 2;
	var floorRating = Math.floor(roundRating);

	for (var i=1; i <= roundRating; i++){
		this.starTypes[i] = this.imgPath + 'rating_on.gif';
	};

	if (floorRating != roundRating) {
		this.starTypes[floorRating + 1] = this.imgPath + 'rating_half.gif';
		floorRating++;
	};	
	
	for (var i = floorRating + 1; i <= 5; i++){
		this.starTypes[i] = this.imgPath + 'rating_off.gif';
	};
}

Rating.prototype.createStars = function (){
	this.div.innerHTML = "";
	this.recalculateStars(this.rating);
	
	var thisCopy = this;	
	for (var i = 1; i <= 5; i++){
		this.stars[i] = document.createElement("IMG");
		this.stars[i].ratingNum = i;
		this.stars[i].src = this.starTypes[i];
		this.stars[i].width = 10;
		this.stars[i].height = 10;
		this.stars[i].border = 0;
		this.stars[i].alt = i;
		this.stars[i].onmouseover = function() { if (thisCopy.enabled) thisCopy.mouseOver(this.ratingNum) };
		this.stars[i].onmouseout = function() { if (thisCopy.enabled) thisCopy.mouseOut(this.ratingNum) };
		this.stars[i].onclick = function() { if (thisCopy.enabled) thisCopy.mouseClick(this.ratingNum) };
		this.div.appendChild(this.stars[i]);
	};	
};

Rating.prototype.mouseOver = function (num){
	for (var i=1; i <= num; i++){
		this.stars[i].src = this.imgPath + 'rating_over.gif';
	};
};

Rating.prototype.mouseOut = function (num){
	for (var i=1; i <= 5; i++){
		this.stars[i].src = this.starTypes[i];
	};
};

Rating.prototype.mouseClick = function (num){
	if (this.enabled) {
		$(this.div).fadeOut(300);
		var newRating = $.ajax({
		type: "GET",
		url: "/"+this.file,
		data: {
			id: this.intId,
			point : num,
			action : 'vote',
			controller : this.controller,
			ajax : 'true'
		},
		async: false
		}).responseText;
		var data = eval('('+newRating+')');
		if (data.status == 'true') {
			this.recalculateStars(parseInt(data.rating));
		}
		for (var i=1; i <= 5; i++){
			this.stars[i].src = this.starTypes[i];
		};
		this.enabled = false;
		var countrating = $('#countrating_'+this.intId).html();
		$('#countrating_'+this.intId).html(parseInt(countrating)+1);
		$(this.div).fadeIn(300);
		if (this.notifier) this.notifier.hide();
	};
};


function fc_submit(form_title, url, divId, fc_data){
	if (notifier) notifier.display("Please wait...");

	$.ajax({
		type: "GET",
		dataType: "xml",
		url: url,
		data: fc_data,
		async: "true",
		success: function(xml) {
			if (notifier) notifier.hide();
			var blankFieldsPresent = emailInvalid = error = false;
			var responseTxt = "";
			$(xml).find("returnedData > errors > error").each(function(){
				if ($(this).attr("type") == "blank") {
					blankFieldsPresent = true;
					error = true;
				}
				
				if ($(this).attr("type") == "validate") {
					emailInvalid = true;
					error = true;
				}
				
				if ($(this).attr("type") == "validate") {
					emailInvalid = true;
					error = true;
				}
				
				if ($(this).attr("type") == "already_registered") {
					responseTxt += "You have already registered with us.\n\n";
					error = true;
				}

			});
			if (blankFieldsPresent) {
				responseTxt += "Please fill all required fields.\n\n";
			};
			if (emailInvalid) {
				responseTxt += "E-mail Address is invalid.\n\n";
			};
			
			if (!error) {
				$(xml).find("returnedData > message").each(function(){
					if ($(this).attr("type") == "thank") {
						responseTxt += "<br/><div align='Center'>Thank you for your interest.<br/>You will be hearing from us soon.</div>";
						document.getElementById(divId).innerHTML = responseTxt;
					} else {
						error = true;
					}
				});
				
				if (error) {
					responseTxt += "Unknown error, please try again later.\n\n";
				};
			};

			if (error) {
				alert(form_title + ":\n\n" + responseTxt);
			};
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			if (notifier) notifier.hide();
			alert(form_title + ": an error occured while connecting to the server, please try again later.\n\n");
		}
	});
}

function before() {
}

function rand( min, max ) {
    if( max ) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    } else {
        return Math.floor(Math.random() * (min + 1));
    }
}


/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

	$(function(){
		ajax('/?controller=user&action=rightpart&ajax=true', 'GET', '', before, successrightpart);
		/*ajax('/?controller=shop&action=globaldata&ajax=true', 'GET', '', before, successleftgoods);*/
		/*if(typeof no_map == 'undefined')
		ajax('/map.php?action=filter&ajax=true', 'GET', '', before, successtopminisites);*/
	});