﻿var lock = false;
var fail = true;
var first_time = true;
var share_str = "";
var first_share = true;
var download = false;
$(function() {
    //addLog('visit', 1);
    isRegister();

    // Email поля ввода
    //-------------------------------------
     var mail_login = $('#mail_login').val();
     var email_inp = $('#email').val();
     var mail_pass = $('#mail_pass').val();
     $('#email').click(function(e) {
            data = $(this).val();
           if(data == email_inp){
              $(this).val('');
           }
           e.preventDefault();
      });
     $('#email').blur(function() {
            if($(this).val() == '') {
              $(this).val(email_inp);
            }
            launch(true);
     });

      $('#mail_login').click(function(e) {
            data = $(this).val();
           if(data == mail_login){
              $(this).val('');
           }
           e.preventDefault();
      });
     $('#mail_login').blur(function() {
            if($(this).val() == '') {
              $(this).val(mail_login);
            }
     });
     $('#mail_pass').click(function(e) {
            data = $(this).val();
           if(data == mail_pass){
              $(this).val('');
           }
           e.preventDefault();
      });
     $('#mail_pass').blur(function() {
            if($(this).val() == '') {
              $(this).val(mail_pass);
            }
     });
    //-------------------------------------
	$('.items div a').click(function() {
		$('html, body').animate({ scrollTop: 80 }, 500);
	});
	$(".sociallinks a").click(function(){
        fail = false;
		$("#download-button").addClass("download-button");
        });
	if(!getCookie('email')){
       $(".sociallinks a").css('opacity', '0.2');
    }

	//Подсветка выбранной соц сети

	$("a.vk").click(function(){
        if(!first_share) share_str = share_str + ',';
        share_str = share_str + 'vk';
        first_share = false;
		$(this).css("background-position", "-612px -249px");
        addLog('click_vk',8);
	});
	$("a.mailru").click(function(){
        if(!first_share) share_str = share_str + ',';
	    share_str = share_str + 'mr';
        first_share = false;
		$(this).css("background-position", "-667px -249px");
        addLog('click_mail',9);
	});
	$("a.fb").click(function(){
	    if(!first_share) share_str = share_str + ',';
	    share_str = share_str + 'fb'
        first_share = false;;
		$(this).css("background-position", "-722px -249px");
        addLog('click_facebook',10);
	});
	$("a.ok").click(function(){
	   if(!first_share) share_str = share_str + ',';
	    share_str = share_str + 'ok';
        first_share = false;
		$(this).css("background-position", "-777px -249px");
        addLog('click_odkl',11);
	});
	$("a.twitter").click(function(){
	    if(!first_share) share_str = share_str + ',';
        share_str = share_str + 'tw';
        first_share = false;
		$(this).css("background-position", "-832px -249px");
        addLog('click_twiter',12);
	});

	$("#download-button").click(function(){
		if(fail) return;
        sendRegister(share_str);
	});
	$(".submit").click(function(){
        sendLogin();
        return false;
	});

    //Cкрытие маски

	$(".mask, .closemodal").click(function(){
	   if(download) window.location.reload();
       // $('.tabsheader').show();
		$(".mask").fadeOut(500);
		$(".modal").fadeOut(500);
        $(".modal_reg").fadeOut(500);
        $('#email').val(email_inp);
        $('.okay').hide();
        $('.false').hide();
        $(".onsocial").show();
        $(".sociallinks a").stop();
        $(".sociallinks a").css('opacity', '0.2');
        $("#download-button").removeClass("download-button");
        $("#download-button").fadeIn(500);
		$(".regok").hide();
		$(".tabsheader").fadeOut(500);
        $("#logintab").hide();
        $('#inp_wrong').hide();
        fail = true;
	});
    //-------------------------------
	$('#email').keyup(function(){
        launch(false);
	});

    //Отправка запроса на вспомнить пароль

    $('#rem_pass').click(function(){
        sendRemPass($('#email').val());
    });
     $('#rem_pass_login').click(function(){
        sendRemPass($('#mail_login').val());
    });

    //----------------------------------

	$(".slider").scrollable({circular: true});

	$(".tabsheader a").click(function() {
		$(".tabsheader a").each(function() {
			$(this).removeClass("current");
		});
		$(this).addClass("current");
	});

	$("#regtabhead").click(function(){
		$("#logintab").hide();
		$("#regtab").fadeIn(500);
		return false;
	});
	$("#logintabhead").click(function(){
		$("#regtab").hide();
		$("#logintab").fadeIn(500);
		return false;
	});

    $('.forum-button').click(function(e){
        e.preventDefault();
        addLog('click_forum',6);
        window.location.href = $(this).attr('href');
    });
    $('#install_link').click(function(e){
        addLog('download_install',4);
        e.preventDefault();
        window.location.href = $(this).attr('href');
    });
    $('#torent_link').click(function(e){
        addLog('download_torent',3);
        e.preventDefault();
        window.location.href = $(this).attr('href');
    });
    $('.items div a').lightBox({
		imageBtnClose: $('#box').text() + 'close.png',
		imageBtnPrev: $('#box').text() + 'lightbox-btn-prev.png',
		imageBtnNext: $('#box').text() + 'lightbox-btn-next.png',
		imageLoading: $('#box').text() + 'lightbox-ico-loading.gif',
		txtImage: 'Изображение',
		txtOf: 'из'
	});

});
$(document).ready(function() {
    $('#play').click(function(){
        modalopen();
    });
    $('#game').click(function(){
        gameClick();
    });
 });

$(window).load(function() {
	var theWindow        = $(window),
		$bg              = $("#bg"),
		aspectRatio      = $bg.width() / $bg.height();

		$('#bg').show();

	function resizeBg() {
		if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
			$bg
				.removeClass()
				.addClass('bgheight');
		} else {
			$bg
				.removeClass()
				.addClass('bgwidth');
		}
	}

	theWindow.resize(function() {
			resizeBg();
	}).trigger("resize");

	$(".slider").scrollable({circular: true});
        loadBlock(168);

});
function launch(tmp) {

    var mail = $('#email').val();
        if(mail.isValidEmail()) {
            if(tmp) addLog('valid_email',5, mail);
            $('#inp_wrong').hide();
            $('#email').removeClass('invalid');
            $('.social .false').hide();
            $('.social .okay').show();
            $(".sociallinks a").stop();
            $(".sociallinks a").animate({opacity : 1},2000);
            $(".onsocial").hide();
        } else {
            fail = true;
            $('#inp_wrong').hide();
            $("#download-button").removeClass("download-button");
            $("#download-button").fadeIn(500);
            $('#email').addClass('invalid');
            $('.social .okay').hide();
            $('.social .false').show();
            $(".onsocial").show();
            $(".sociallinks a").stop();
            $(".sociallinks a").animate({opacity : 0.2},1);
        }
}
function login() {
    mail = $('#email_login').val();
    pass = $('#email_pass').val();
        if(mail.isValidEmail()) {
            $('.login .okay').show();
            $('.login .false').hide();
            sendLogin(mail, pass);
        } else {
            $('.login .okay').hide();
            $('.login .false').show();
        }
}
function modalopen() {
    addLog('test',2);
	$(".mask").fadeIn(500);
    $('#email').removeClass('invalid');
	var windowHeight = $("#container").height() + 14;

	$(".mask").height(windowHeight);
	$(".modal").fadeIn(500);
	$(".social").show();
	$(".tabsheader").fadeIn(500);
	$(".tabsheader a").each(function() {
		$(this).removeClass("current");
	});
	$("#regtabhead").addClass("current");

}
function gameClick(){
    addLog('download_install',4);
    window.location.href = $('#login_link').val();
}
function register() {
    var mail = $('#email').val();
    var JSONOObject = [mail];
    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'Subscribes',
        'addMail',
        JSONOString,
        function sucsess(data) {
            if(data){
                setCookie('email', mail);
            }
        },
        function fail(data) {
            lock = false;
        }
    );
}
function isRegister() {
   var mail = getCookie('email');

   var href = getCookie('href');
    if(mail){
        first_time = false;
        $('#testbutton').hide();
        $('.forshare').show();
        $('#logged').show();
        $('#login_link').val(href);
    } else {
        first_time = true;
        $('#testbutton').show();
        $('.forshare').hide();
        $('#logged').hide();
    }

}
function loadBlock($id) {
  var JSONOString = JSON.stringify();
  AJAXBlockLoad(
      $id,
      JSONOString,
      function success(data) {
          $('#holder').html(data.html);
          ODKL.init();

      },

      function error(data) {
       //  spr(22);
      }
  );
}
function sendRemPass(mail) {
    var JSONOObject = [mail];
    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'api',
        'rememberPass',
        JSONOString,
        function sucsess(data) {
            if(data=='Ok'){
                $('#ok_pass').show();
                $('#fail_pass').hide();
                $('.passwordsent').fadeIn(700, function (){
                    setTimeout("$('.passwordsent').fadeOut(500)", 2000);
                });

            } else {
                $('#fail_pass').show();
                $('#ok_pass').hide();
                $('.passwordsent').fadeIn(700, function (){
                    setTimeout("$('.passwordsent').fadeOut(500)", 2000);
                });
            }
        },
        function fail(data) {
            return false;
        }
    );
}
function sendDownload() {
    var mail = $('#email').val();
    $('.preloaderbox').show();
    var JSONOObject = [mail];
    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'api',
        'download',
        JSONOString,
        function sucsess(data) {
            if(data){
                 $('.preloaderbox').hide();
            } else {

            }
        },
        function fail(data) {
            return false;
        }
    );
}
function sendLogin() {
   var mail = $('#mail_login').val();
   var pass = $('#mail_pass').val();
    $('.preloaderbox').show();
    var JSONOObject = [mail, pass];
    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'api',
        'login',
        JSONOString,
        function sucsess(data) {
            if(data){
                 $('.preloaderbox').hide();
                 expires = new Date(); // получаем текущую дату
                 expires.setTime(expires.getTime() + (1000 * 86400 * 365)); // вычисляем срок хранения cookie
                 setCookie('email', mail,expires);
                 setCookie('href', data,expires);
                 window.location.reload();

            } else {
                $('.preloaderbox').hide();
                $('#login_wrong').show();
            }
        },
        function fail(data) {
            return false;
        }
    );
}
function sendRegister(share_str) {
    var d1 = new Date();
    var mail = $('#email').val();
    var params = $('#params').val();
    $('.preloader').show();
    var JSONOObject = [mail, share_str, params];
    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'api',
        'register',
        JSONOString,
        function sucsess(data) {
            if(data){
                var d2 = new Date();
                var dt=(d2.getTime()-d1.getTime())/1000;
                addLog('click_download',7,dt);
                expires = new Date(); // получаем текущую дату
                expires.setTime(expires.getTime() + (1000 * 86400 * 365)); // вычисляем срок хранения cookie
                setCookie('email', mail,expires);
                setCookie('href', data,expires);
                $('.preloader').hide();
                $(".social").hide();
                $("#installer").show();
                $('#install_link').attr('href', data);
                $('#login_link').val(data);

                 download = true;
                  //$('.tabsheader').hide();
                 $(".regok").fadeIn(50);
                 $(".regok").append('<img src="http://pix.am10.ru/img.php?rid=20221">');

            } else {
                $('#inp_wrong').show();
                $('.social .okay').hide();
                $('.social .false').show();
                $('.preloaderbox').hide();
            }
        },
        function fail(data) {
            return false;
        }
    );
}
function addLog(text,type,param) {
    if(param == undefined) {
        param = 0;
    }
    var JSONOObject = [text, type, param];
    var JSONOString = JSON.stringify(JSONOObject);
    AJAXRequest(
        'log',
        'addLog',
        JSONOString,
        function sucsess(data) {
            if(data){

            } else {

            }
        },
        function fail(data) {
            return false;
        }
    );
}
function confirmField(){
    var mail = $('#email').val();
        if(mail.isValidEmail()) {
            addLog('valid_email',5);
            $('#inp_wrong').hide();
            $('#email').removeClass('invalid');
            $('.social .false').hide();
            $('.social .okay').show();
            $(".sociallinks a").stop();
            $(".sociallinks a").animate({opacity : 1},2000);
            $(".onsocial").hide();
        } else {
            fail = true;
            $('#inp_wrong').hide();
            $("#download-button").removeClass("download-button");
            $("#download-button").fadeIn(500);
            $('#email').addClass('invalid');
            $('.social .okay').hide();
            $('.social .false').show();
            $(".onsocial").show();
            $(".sociallinks a").stop();
            $(".sociallinks a").animate({opacity : 0.2},1);
        }
}
/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CCAttribution-ShareAlike 2.5 Brazil - http://creativecommons.org/licenses/by-sa/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */
(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.8,fixedNavigation:false,imageLoading:'images/lightbox-ico-loading.gif',imageBtnPrev:'images/lightbox-btn-prev.gif',imageBtnNext:'images/lightbox-btn-next.gif',imageBtnClose:'images/lightbox-btn-close.gif',imageBlank:'images/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Image',txtOf:'of',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
    function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
        while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
        _set_image_to_view();}
    function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({'top':'100px',left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
    function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
        var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
        $('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
        if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
    function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
        if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
        _enable_keyboard_navigation();}
    function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
    function _disable_keyboard_navigation(){$(document).unbind();}
    function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
        key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
        if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
        if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
    function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
        if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
    function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
    function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
        var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
            windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
        if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
        if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
        arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
        arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
    while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);


// AJAX //

/*
 http://www.JSON.org/json2.js
 2010-08-25

 Public Domain.

 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

 See http://www.JSON.org/js.html


 This code should be minified before deployment.
 See http://javascript.crockford.com/jsmin.html

 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
 NOT CONTROL.


 This file creates a global JSON object containing two methods: stringify
 and parse.

 JSON.stringify(value, replacer, space)
 value       any JavaScript value, usually an object or array.

 replacer    an optional parameter that determines how object
 values are stringified for objects. It can be a
 function or an array of strings.

 space       an optional parameter that specifies the indentation
 of nested structures. If it is omitted, the text will
 be packed without extra whitespace. If it is a number,
 it will specify the number of spaces to indent at each
 level. If it is a string (such as '\t' or '&nbsp;'),
 it contains the characters used to indent at each level.

 This method produces a JSON text from a JavaScript value.

 When an object value is found, if the object contains a toJSON
 method, its toJSON method will be called and the result will be
 stringified. A toJSON method does not serialize: it returns the
 value represented by the name/value pair that should be serialized,
 or undefined if nothing should be serialized. The toJSON method
 will be passed the key associated with the value, and this will be
 bound to the value

 For example, this would serialize Dates as ISO strings.

 Date.prototype.toJSON = function (key) {
 function f(n) {
 // Format integers to have at least two digits.
 return n < 10 ? '0' + n : n;
 }

 return this.getUTCFullYear()   + '-' +
 f(this.getUTCMonth() + 1) + '-' +
 f(this.getUTCDate())      + 'T' +
 f(this.getUTCHours())     + ':' +
 f(this.getUTCMinutes())   + ':' +
 f(this.getUTCSeconds())   + 'Z';
 };

 You can provide an optional replacer method. It will be passed the
 key and value of each member, with this bound to the containing
 object. The value that is returned from your method will be
 serialized. If your method returns undefined, then the member will
 be excluded from the serialization.

 If the replacer parameter is an array of strings, then it will be
 used to select the members to be serialized. It filters the results
 such that only members with keys listed in the replacer array are
 stringified.

 Values that do not have JSON representations, such as undefined or
 functions, will not be serialized. Such values in objects will be
 dropped; in arrays they will be replaced with null. You can use
 a replacer function to replace those with JSON values.
 JSON.stringify(undefined) returns undefined.

 The optional space parameter produces a stringification of the
 value that is filled with line breaks and indentation to make it
 easier to read.

 If the space parameter is a non-empty string, then that string will
 be used for indentation. If the space parameter is a number, then
 the indentation will be that many spaces.

 Example:

 text = JSON.stringify(['e', {pluribus: 'unum'}]);
 // text is '["e",{"pluribus":"unum"}]'


 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

 text = JSON.stringify([new Date()], function (key, value) {
 return this[key] instanceof Date ?
 'Date(' + this[key] + ')' : value;
 });
 // text is '["Date(---current time---)"]'


 JSON.parse(text, reviver)
 This method parses a JSON text to produce an object or array.
 It can throw a SyntaxError exception.

 The optional reviver parameter is a function that can filter and
 transform the results. It receives each of the keys and values,
 and its return value is used instead of the original value.
 If it returns what it received, then the structure is not modified.
 If it returns undefined then the member is deleted.

 Example:

 // Parse the text. Values that look like ISO date strings will
 // be converted to Date objects.

 myData = JSON.parse(text, function (key, value) {
 var a;
 if (typeof value === 'string') {
 a =
 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
 if (a) {
 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
 +a[5], +a[6]));
 }
 }
 return value;
 });

 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
 var d;
 if (typeof value === 'string' &&
 value.slice(0, 5) === 'Date(' &&
 value.slice(-1) === ')') {
 d = new Date(value.slice(5, -1));
 if (d) {
 return d;
 }
 }
 return value;
 });


 This is a reference implementation. You are free to copy, modify, or
 redistribute.
 */

/*jslint evil: true, strict: false */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
 lastIndex, length, parse, prototype, push, replace, slice, stringify,
 test, toJSON, toString, valueOf
 */


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                this.getUTCFullYear()   + '-' +
                    f(this.getUTCMonth() + 1) + '-' +
                    f(this.getUTCDate())      + 'T' +
                    f(this.getUTCHours())     + ':' +
                    f(this.getUTCMinutes())   + ':' +
                    f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
            Number.prototype.toJSON =
                Boolean.prototype.toJSON = function (key) {
                    return this.valueOf();
                };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
            typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

                return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

            case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

                if (!value) {
                    return 'null';
                }

// Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

// Is the value an array?

                if (Object.prototype.toString.apply(value) === '[object Array]') {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                            mind + ']' :
                            '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

// If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/
                .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
}());

String.prototype.replaceAll = function(search, replace){
    return this.split(search).join(replace);
}

String.prototype.isValidEmail = function() {
    regexp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    if (!(regexp.test(this))) {
        return false;
    } else {
        return true;
    }
}

function spr(value){

    if(typeof console == 'object'){
        console.log(value);
    } else if(typeof window == 'object'){
        window.log(value);
    }

}

function log(value) {
    spr(value);
}

function getCookie(name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset)
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
    return(setStr);
}


function setCookie (name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function include(url){
    var element;
    switch(url.split(".").pop()){
        case "css":{
            element=document.createElement("link");
            element.setAttribute("rel","stylesheet");
            element.setAttribute("type","text/css")
            element.setAttribute("href",url)
        }break;
        case "js":{
            element=document.createElement("script");
            element.setAttribute("language","javascript")
            element.setAttribute("src",url)
        }break;
        default:window.console && window.console.error("could not identify",url,"skip include");return;
    }
    var head=document.querySelector("head");
    if(head.innerHTML.indexOf(element.outerHTML)!=-1){
        window.console && window.console.warn("Duplicate include, skipping:",url);
    }else{
        head.appendChild(element);
    }
}


function AJAXRequest(className, methodName, jsonData, successFunc, errorFunc){
    var JSONOString = JSON.stringify(jsonData);
    $.ajax({
        type : 'POST',
        url  : document.domain,
        dataType : 'json',
        data: {
            JSON        : JSONOString,
            AJAXRequest : true,
            className   : className,
            methodName  : methodName
        },
        success : successFunc,
        error : errorFunc
    });

    return false;
}

function AJAXBlockLoad(BlockID, params, successFunc, errorFunc){
    var JSONOString = JSON.stringify(params);
    $.ajax({
        type : 'POST',
        url  : document.domain,
        dataType : 'json',
        data: {
            JSON        : JSONOString,
            AJAXRequest : true,
            BlockId     : BlockID
        },
        success : successFunc,
        error : errorFunc
    });

    return false;
}



/*
 * request example
 */
function sendRequest() {

    JSONOObject = {key1 : 'value1', key2 : {key3 :'value3', key4 : 'value4'}};

    /*you can also use arry*/
    someArray = Array(1,2,3);

    var JSONOString = JSON.stringify(JSONOObject);

    AJAXRequest(
        'xGalleryRating',
        'changeRating',
        JSONOString,
        function log(data) {
            // //console.log(data);
        }
    );
}

function lockDisplay(opac, speed) {
    if(opac <= 0.4){
        $("#loader").attr('src', $('#light').html());
        $("#blockUI").css({'background-color': ''});
    } else{
        $("#blockUI").css({opacity: opac});
    }
    if ($('#blockUI') != undefined) {
        $('#blockUI').fadeIn(speed);
    }
}

function unlockDisplay(speed, message) {
    if ($('blockUI') != undefined) {
        $('#blockUI').fadeOut(speed, function() {
            showMessage(message);
        });
    } else {
        showMessage(message);
    }
}
/*
 function unlockDisplay(speed) {
 if ($('blockUI') != undefined) {
 $('#blockUI').fadeOut(speed, function() {
 });
 }
 }
 */
