function newImg(i){
    p=new Image();
    p.src=i;
    return p;
}
var cookie_options = {
    path: '/', 
    expires: 365
};

function trim( str, charlist ) {
    charlist = !charlist ? ' ' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    var re = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
    return str.replace(re, '');
}

/***********************************************************************************/

function str_replace(search, replace, subject) {
    var s = subject;
    var f = [].concat(search);
    var r = [].concat(replace);
    var l = (f.length>r.length) ? r.length : f.length;
    var i = 0;

    for (i=0; i<l; ++i)
    {
        s = s.split(f[i]).join(r[i]);
    }

    return s;
}
function explode( delimiter, string ) {    // Split a string by string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: kenneth
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

    var emptyArray = {
        0: ''
    };

    if ( arguments.length != 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
        {
        return null;
    }

    if ( delimiter === ''
        || delimiter === false
        || delimiter === null )
        {
        return false;
    }

    if ( typeof delimiter == 'function'
        || typeof delimiter == 'object'
        || typeof string == 'function'
        || typeof string == 'object' )
        {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    return string.toString().split ( delimiter.toString() );
}
/***********************************************************************************/

function refreshSecretkey(id,type)
{
    if(typeof(type)=='undefined'){
        setTimeout("refreshSecretkeyTimeout('"+id+"')",100);
    }else{
        setTimeout("refreshSecretkeyTimeout('"+id+"','"+type+"')",100);
    }
}
function refreshSecretkeyTimeout(id,type)
{
    if(typeof(type)=='undefined'){
        $('#'+id).attr({
            'src':'/secretkey.php?id='+Math.round(Math.random(0)*1000)+1
        });
    }else{
        $('#'+id).attr({
            'src':'/secretkey.php?type='+type+'&id='+Math.round(Math.random(0)*1000)+1
        });
    }
}

/***********************************************************************************/

jQuery.validator.addMethod("validemail", function(value, element, param) {
    if(trim(value)=='' && this.optional(element)==false)return false;
    var reg = /^[0-9a-z_\.-]+@[0-9a-z_^\.-]+\.[a-z]{2,6}$/i
    return this.optional(element) || (reg.test(value) || reg.test(value));
},'Please enter valid email');

//------------------------------------------------------------------------------------

jQuery.validator.addMethod("checkDate", function(value, element, param) {
    //alert(element.id);
    var params = explode(',',param);
    var day=parseInt($('#'+params[0]).val());
    var month=parseInt($('#'+params[1]).val())-1;
    var year=parseInt($('#'+element.id).val());
    if(!this.optional(element) && (day+month+year==-1))return true;
    var date = new Date( year, month, day )
    if((day==date.getDate())&&(month==date.getMonth())&&(year==date.getFullYear())&&(year>1753))
    {
        return true;
    }
    return false;
});
//------------------------------------------------------------------------------------
jQuery.validator.addMethod("secretkey",  function(value, element, param) {
    if(trim(value)=='' && this.optional(element)==false)return true;
    var reg = /^[a-z0-9_-]+$/i
    return reg.test(value) || reg.test(value);
}, 'Please enter valid secretkey!');
jQuery.validator.addMethod("checkAge", function(value, element, param) {
    var params = explode(',',param);
    var day=parseInt($('#'+params[0]).val());
    var month=parseInt($('#'+params[1]).val())-1;
    var year=parseInt($('#'+element.id).val());
    var ageStart = params[2];
    var ageEnd   = params[3];
    //alert(ageStart+ ' '+ageEnd);
    if(!this.optional(element) && (day+month+year==-1))return true;
    var date = new Date( year, month, day )
    if((day==date.getDate())&&(month==date.getMonth())&&(year==date.getFullYear())&&(year>1753))
    {
        var nowTime = new Date();
        var date1   = new Date(nowTime.getFullYear()-ageEnd,nowTime.getMonth(), nowTime.getDate());
        var date2   = new Date(nowTime.getFullYear()-ageStart,nowTime.getMonth(), nowTime.getDate());
        return ((date.getTime()>=date1.getTime())&&(date.getTime()<=date2.getTime()));
    }
    return false;
});

//------------------------------------------------------------------------------------

jQuery.validator.addMethod("validnickname", function(value, element, param) {
    if(value=='')return false;
    var reg = /^[a-zA-Z0-9_]+$/i
    return reg.test(value) || reg.test(value);
}, 'Please enter valid nickname!');

jQuery.validator.addMethod("validlatin", function(value, element, param) {
    //alert(element.id+' '+this.optional(element));
    if(trim(value)=='' && this.optional(element)!=false)return true;
    var reg = /^[a-z0-9!@%#$\^&*()\[\]+_=<>?.\/\\{}~"'’`:;,| \r\n\t~¢£¤¥¦§¨©«¬®¯°±²³´·¸¹º»ǀǁǂ\‒\–\—\―‖‗‘’‚‛“”„‟†‡•…′″‴‹›₤€₵℅ℓ№℗™■□▪▫◊○◌●◦-]+$/i

    //var reg = /^[a-zA-Z!@%#$^&*()[\]+_=<>?./\{}~"'’`:;,| \r\n\t-]+$/i
    //@[\]^_`{|}~¢£¤¥¦§¨©«¬­®¯°±²³´·¸¹º»ǀǁǂ‒–—―‖‗‘’‚‛“”„‟†‡•…′″‴‹›₤€₵℅ℓ№℗™■□▪▫◊○◌●◦
    return reg.test(value) || reg.test(value);
}, 'Please enter latin symbols only!');


function processXml(responseXML, form_id, callback_function) {
    var form = $('#'+form_id);
    $('[id^=error_]',form).hide();
    var count_errors = 0;
    $('e', responseXML).each(function(i){
        count_errors++;
        var container	= $('c',$(this)).text();
        var message		= $('m',$(this)).text();
        if(container==form_id+'_secretkey'){
            var s=explode('Form',container);
            refreshSecretkey(form_id+'_secretkey_img',s[0]);
        }
        $('#error_'+container).html(message).show();
    });
    if(count_errors==0 && typeof(callback_function)=='function'){
        callback_function(form_id);
    }
}








var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version)
    {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful.

            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }

    return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if ( isIE && isWin && !isOpera ) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
    versionStr = GetSwfVer();
    if (versionStr == -1 ) {
        return false;
    } else if (versionStr != 0) {
        if(isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
            tempString        = tempArray[1];			// "2,0,0,11"
            versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
        } else {
            versionArray      = versionStr.split(".");
        }
        var versionMajor      = versionArray[0];
        var versionMinor      = versionArray[1];
        var versionRevision   = versionArray[2];

        // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(reqMajorVer)) {
            return true;
        } else if (versionMajor == parseFloat(reqMajorVer)) {
            if (versionMinor > parseFloat(reqMinorVer))
                return true;
            else if (versionMinor == parseFloat(reqMinorVer)) {
                if (versionRevision >= parseFloat(reqRevision))
                    return true;
            }
        }
        return false;
    }
}
var FlashInstalled = GetSwfVer()!=-1;
var FlashValid     = DetectFlashVer(9,0,24);
function notLatinHandler(el){
    $('#'+el).autotab({
        format: 'latin'
    });
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
function sendToActionScript(player,value) {
    setTimeout('thisMovie("'+player+'").sendTextToFlash("'+value+'")',1000);
}


$(document).ready(function(){
    $('#loginForm').submit(function() {
        setTimeout(function(){
            if($('#loginForm_login').hasClass('error'))
                alert('Ваш логін: ' + $('#error_loginForm_login').html());
            if($('#loginForm_password').hasClass('error'))
                alert('Ваш пароль: ' + $('#error_loginForm_password').html());
        },20);
    });
});

function block_ch(el, t, url, id) {
    if($.cookie('voted')==undefined){
        var voted = new Array();
    }else{
        var voted= explode('#',$.cookie('voted'));
    }
    for(var k in voted){
        var v= voted[k];
        var vv=explode(':',v);
        if(vv[0]==id){
            return false;
        }
    }
    $(el).prev().removeClass('off');
    //voted[voted.length]=id + ':'+(t ? 1 : 0);
    //$.cookie('voted', voted.join('#'), cookie_options);

    if(t){
        document.location=url+'?do=up';
    }else{
        document.location=url+'?do=down';
    }
}

function block_unch(i) {
    document.getElementById('block-ch_'+i).style.display='block';
    document.getElementById('block-chu_'+i).style.display='none'
}

























/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
var intVal=null;
function menu_on() {
    $('#menuCh1').hide();
    $('#menuCh1Sub').show();
	clear_int();
}
function clear_int() {
    clearTimeout(intVal);
}
   function menu_off() {
    intVal = setTimeout(menu_off2,200);
   }
   function menu_off2() {
    $('#menuCh1').show();
    $('#menuCh1Sub').hide();
   }
*/

var intVal=null;
function menu_on() {
    $('#menuCh1').hide();
    $('#menuCh1Sub').show();
    clear_int();
}
function clear_int() {
    clearTimeout(intVal);
}
function menu_off() {
    intVal = setTimeout(menu_off2,1000);
}
function menu_off2() {
    $('#menuCh1').show();
    $('#menuCh1Sub').hide();
}
	
$(document).ready(function(){
	
    $('#loginForm_login').click(function(){
        if(!$(this).hasClass('active'))
            $(this).addClass('active');
    });
	
    $('#loginForm_password').click(function(){
        if(!$(this).hasClass('active'))
            $(this).addClass('active');
    });

    $('.videoLink').click(function(){
														   
        $(this).parent().find('.video').toggle();
        $(this).find('.videoArrow').toggleClass('videoArrowDown');
    });

    $('.addrecipeLink').click(function(){
														   
        $(this).parent().find('.addRecipeForm').toggle();
        $(this).find('.recipeArrow').toggleClass('recipeArrowDown');
    });
})

function createUploadContainer(content_type,container_type,file_container,session_id,ext1,ext2,maxsize){
    maxsize = parseInt(maxsize)*1024*1024;
    $(document).ready(function() {
        if(FlashInstalled /*&& FlashValid*/){
            $('#'+file_container).uploadify({
                'uploader'  : '/js/jquery.uploadify-v2.1.4/uploadify.swf',
                'script'    : '/importer.php',
                'cancelImg' : '/js/jquery.uploadify-v2.1.4/remove.gif',
                'buttonImg' : '/js/jquery.uploadify-v2.1.4/button_upload.gif',
                'expressInstall' :'/js/jquery.uploadify-v2.1.4/scripts/expressInstall.swf',
                'fileDesc'  : ext2,
                'fileExt'  : ext1,
                'sizeLimit':maxsize,
                'rollover'  : true,
                'wmode'     : 'transparent',
                'auto'      : true,
                'width'     : 190,
                'height'    : 22,
                'onComplete'  : function(event,queueID,fileObj,response,data){
                    refreshImportList(content_type,container_type);
                },
                'scriptData':{
                    "SESSION_KEY" : session_id,
                    "do":"upload",
                    "hash":Math.random(),
                    'content_type':content_type,
                    'container_type':container_type
                }
            });
        }else{
        // $('#'+file_container).attr('size','33');
        }
        refreshImportList(content_type,container_type);
    });
    

}


function refreshImportList(content_type,container_type, without_delete){
    var id = content_type+'_'+container_type;
    without_delete = without_delete || 0;
    //alert(container_type);
    for(var k=1;k<=7;k++){
        if(container_type=='s2_photo1-'+k||container_type=='s2_photo2-'+k||container_type=='s2_video1-'+k||container_type=='s2_video2-'+k)
            $('input[name^=s2_photo_video-'+k+']').val(Math.random());
        else if(container_type=='s2_license-'+k)
            $('input[name^=s2_license_hf-'+k+']').val(Math.random());
    }
    $.post('/importer.php',{
        'do'    : 'get_list',
        'without_delete':without_delete,
        content_type:content_type,
        container_type:container_type
    },function(data){
        $('#'+id+'_container').html(data);
    });
}

function DeleteImportFile(video_file,content_type,container_type){
    if(confirm('Are you sure?')){
        var id = content_type+'_'+container_type;
        $.post('/importer.php',{
            'do'    : 'delete',
            video_file:video_file,
            content_type:content_type,
            container_type:container_type
        },function(data){
            refreshImportList(content_type,container_type);
        });
    }
}


jQuery.validator.addMethod("checkAge", function(value, element, param) {
    var params = explode(',',param);
    var day=parseInt($('#'+params[0]).val());
    var month=parseInt($('#'+params[1]).val())-1;
    var year=parseInt($('#'+element.id).val());
    var ageStart = params[2];
    var ageEnd   = params[3];
    //alert(ageStart+ ' '+ageEnd);
    if(!this.optional(element) && (day+month+year==-1))return true;
    var date = new Date( year, month, day )
    if((day==date.getDate())&&(month==date.getMonth())&&(year==date.getFullYear())&&(year>1753))
    {
        var nowTime = new Date();
        var date1   = new Date(nowTime.getFullYear()-ageEnd,nowTime.getMonth(), nowTime.getDate());
        var date2   = new Date(nowTime.getFullYear()-ageStart,nowTime.getMonth(), nowTime.getDate());
        return ((date.getTime()>=date1.getTime())&&(date.getTime()<=date2.getTime()));
    }
    return false;
});

function setupCalendar(ico_calendar_id,sel_days_id,sel_month_id,sel_year_id){
    var ageEnd=36;
    var ageStart=16;
    var nowTime = new Date();
    var date1   = new Date(nowTime.getFullYear()-ageEnd,nowTime.getMonth(), nowTime.getDate());
    var date2   = new Date(nowTime.getFullYear()-ageStart,nowTime.getMonth(), nowTime.getDate());
    var startDate=date1.getDate()+'/'+(date1.getMonth()+1)+'/'+date1.getFullYear();
    var endDate=date2.getDate()+'/'+(date2.getMonth()+1)+'/'+date2.getFullYear();
    // initialise the "Select date" link
    $('#'+ico_calendar_id)
    .datePicker(
    // associate the link with a date picker
    {
        createButton:false,
        startDate:startDate,
        endDate:endDate
    }
    ).bind(
        // when the link is clicked display the date picker
        'click',
        function()
        {
            //alert($(this).dpGetSelected()[0]);
            updateSelects($(this).dpGetSelected()[0]);
            $(this).dpDisplay();
            return false;
        }
        ).bind(
        // when a date is selected update the SELECTs
        'dateSelected',
        function(e, selectedDate, $td, state)
        {
            updateSelects(selectedDate);
        }
        ).bind(
        'dpClosed',
        function(e, selected)
        {
            updateSelects(selected[0]);
        }
        );

    var updateSelects = function (selectedDate)
    {
        
        var selectedDate = new Date(selectedDate);
        $('#'+sel_days_id+' option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
        $('#'+sel_month_id+' option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
        $('#'+sel_year_id+' option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
    }
    // listen for when the selects are changed and update the picker
    $('#'+sel_days_id+', #'+sel_month_id+', #'+sel_year_id)
    .bind(
        'change',
        function()
        {
            var d = new Date(
                $('#'+sel_year_id).val(),
                $('#'+sel_month_id).val()-1,
                $('#'+sel_days_id).val()
                );
            $('#'+ico_calendar_id).dpSetSelected(d.asString());
        }
        );
    //updateSelects(date1.getTime());
    $('#'+sel_days_id).trigger('change');
/*
        // default the position of the selects to today
        var today = new Date();
        updateSelects(today.getTime());

        // and update the datePicker to reflect it...
        $('#'+sel_days_id).trigger('change');
        $('#'+sel_years_id).trigger('change');
        $('#'+sel_months_id).trigger('change');*/

}
function setupCalendarForPassport(ico_calendar_id,sel_days_id,sel_month_id,sel_year_id){
    var ageEnd=20;
    var ageStart=0;
    var nowTime = new Date();
    var date1   = new Date(nowTime.getFullYear()-ageEnd,nowTime.getMonth(), nowTime.getDate());
    var date2   = new Date(nowTime.getFullYear()-ageStart,nowTime.getMonth(), nowTime.getDate());
    var startDate=date1.getDate()+'/'+(date1.getMonth()+1)+'/'+date1.getFullYear();
    var endDate=date2.getDate()+'/'+(date2.getMonth()+1)+'/'+date2.getFullYear();
    // initialise the "Select date" link
    $('#'+ico_calendar_id)
    .datePicker(
    // associate the link with a date picker
    {
        createButton:false,
        startDate:startDate,
        endDate:endDate
    }
    ).bind(
        // when the link is clicked display the date picker
        'click',
        function()
        {
            //alert($(this).dpGetSelected()[0]);
            updateSelects($(this).dpGetSelected()[0]);
            $(this).dpDisplay();
            return false;
        }
        ).bind(
        // when a date is selected update the SELECTs
        'dateSelected',
        function(e, selectedDate, $td, state)
        {
            updateSelects(selectedDate);
        }
        ).bind(
        'dpClosed',
        function(e, selected)
        {
            updateSelects(selected[0]);
        }
        );

    var updateSelects = function (selectedDate)
    {

        var selectedDate = new Date(selectedDate);
        $('#'+sel_days_id+' option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
        $('#'+sel_month_id+' option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
        $('#'+sel_year_id+' option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
    }
    // listen for when the selects are changed and update the picker
    $('#'+sel_days_id+', #'+sel_month_id+', #'+sel_year_id)
    .bind(
        'change',
        function()
        {
            var d = new Date(
                $('#'+sel_year_id).val(),
                $('#'+sel_month_id).val()-1,
                $('#'+sel_days_id).val()
                );
            $('#'+ico_calendar_id).dpSetSelected(d.asString());
        }
        );
    //updateSelects(date1.getTime());
    $('#'+sel_days_id).trigger('change');
/*
        // default the position of the selects to today
        var today = new Date();
        updateSelects(today.getTime());

        // and update the datePicker to reflect it...
        $('#'+sel_days_id).trigger('change');
        $('#'+sel_years_id).trigger('change');
        $('#'+sel_months_id).trigger('change');*/

}
function setNotLatinHandlers(form,fields){
    for(f in fields){
        notLatinHandler(form+'_'+fields[f]);
    }
}

function DateFromString(d){
    var p=explode('/',d);
    var date = new Date(p[2],p[1]-1,p[0]);
    return date;
}




function addParticipantRowById(id){
    //alert($(template(id)).html());
    $(template(id)).appendTo("#colform_persons");//
    setupCalendar('celendarBirthDate-'+id,'step1_2Form_s1_2_birth_day-'+id, 'step1_2Form_s1_2_birth_month-'+id, 'step1_2Form_s1_2_birth_year-'+id);
    //setupCalendar('celendarPassportW-'+id,'step1_2Form_s1_2_passport_w_day-'+id, 'step1_2Form_s1_2_passport_w_month-'+id, 'step1_2Form_s1_2_passport_w_year-'+id);
    setupCalendarForPassport('celendarPassportW-'+id,'step1_2Form_s1_2_passport_w_day-'+id, 'step1_2Form_s1_2_passport_w_month-'+id, 'step1_2Form_s1_2_passport_w_year-'+id);
    //setNotLatinHandlers('colForm',new Array('first_name-'+id,'last_name-'+id,'middle_name-'+id,'city-'+id));
    if(id==1){
        $('#participant_delete_'+id).remove();
    }else{
        deleteParticipantContainer(id);
    }

    $('#step1_2Form_s1_2_participant_count').val(id);

}
function addParticipantRow() {
    for(var i=1;i<=20;i++){
        if(!document.getElementById('step1_2Form_s1_2_pib_ua-'+i)){
            addParticipantRowById(i);
            break;
        }
    }
    colform_persons_count++;

    if(colform_persons_count>20){
        $("#addUser").hide();
    }
}

function deleteParticipantContainer(p){
    $('#participant_delete_'+p).css('cursor','pointer');
}
function checkRecommend(){
    if(!FlashInstalled){
        $('.alternativeFile').show();
    }
    $("input[name^='s2_rec-']").click(function(){
        var ch=false;
        $("input[name^='s2_rec-']").each(function(){
            if(this.checked){
                ch=true;
            }
        });
        if(ch){
            $("input[name='s2_rec']").val($(this).val());
        }else{
            $("input[name='s2_rec']").val('');
        }
    });

}
function removeWorkHandler(id){
    $('#work_delete_'+id).css('cursor','pointer');
    
}
function addWorkById(id,session_id){
    $(template(id)).appendTo("#works");
    //setNotLatinHandlers('worksForm',new Array('works_title_eng-'+id,'material-'+id,'size-'+id,'description-'+id));

    if(id<=3){
        $('#work_delete_'+id).remove();

    }else{
        removeWorkHandler(id);
    }
    createUploadContainer('step2','media'+id,'worksForm_file-'+id,session_id,'*.jpg;*.gif;*.png;*.avi;*.mp4;*.mov;*.flv;',"All .jpg .gif .png .avi .mp4 .mov .flv files",'100 MB');
    
}
function addWorkRow(session_id) {
    // alert(session_id);
    for(var i=1;i<=7;i++){
        if(!document.getElementById('step2Form_s2_name-'+i)){
            addWorkById(i, session_id);
            break;
        }
    }
    checkRecommend();
    $('#worksForm_works_count').val(colform_work_count);
    colform_work_count++;
    if(colform_work_count>7){
        $("#add_btn").hide();
    }
}

function checkMedia(){
    if(FlashInstalled){
        for(var i=1;i<=7;i++){
            if(document.getElementById('step2Form_s2_name-'+i)){
                $('#worksForm_photo_video-'+i).val((new Date()).getTime());
            }
        }
    }else{
        for(var i=1;i<=7;i++){
            if(document.getElementById('worksForm_photo_video-'+i)){
                $('#worksForm_photo_video-'+i).val('');
            }
        }
        
    }
}


function changeAppType(app_type_old, app_type_new){
    if(app_type_new==app_type_old)return;
    $('#appType'+app_type_old+'_'+app_type_new).val(app_type_old);
    $('#appType'+app_type_old+'_'+app_type_old).get(0).checked=true;
    if(app_type_new!=app_type_old){
        $('#appBlock'+app_type_old).hide();
        $('#appBlock'+app_type_new).show();
    }else{
        $('#appBlock'+app_type_old).show();
        $('#appBlock'+app_type_new).hide();
    }
}
