var timer;
function funcHideDiv() {
	var divElement = document.getElementById('errmsgblock');
	var divElementNoJs = document.getElementById('errmsgblock_nojs');
	if (divElementNoJs) {divElementNoJs.style.display = 'none';};
	if (divElement) {
		divElement.innerHTML = '';
		divElement.style.display = 'none';
	}
}

function showMessage(msg) {
	if (msg) {
	var divElement = document.getElementById('errmsgblock');
	var divElementNoJs = document.getElementById('errmsgblock_nojs');
	if (divElementNoJs) {divElementNoJs.style.display = 'none';};
	if (divElement) {
		if (timer) {
			clearTimeout( timer );
		}
		divElement.innerHTML = msg;
		divElement.style.display = 'block';
		timer = setTimeout( funcHideDiv, 5000 );
		} else {
			funcHideDiv();
		}
	}
}

function formSubmit (object) {
	//showMessage("Start get....");
	var qString = $("#"+object.id).formSerialize();
	$.post( object.action + '?content-type=application/json', qString, formSubmitResult, 'json');
	return false;
}

function formSubmitResult (data, textStatus) {
	if (data.status) {
//alert(data.form.firstname);
		if (data.json_redirect) {location.replace(data.json_redirect); return false;};
		if (data.error_msg) {
			showMessage( data.error_msg )
		} else if (data.msg) {
			showMessage( data.msg )
		} else {funcHideDiv};
		if (data.form) {
			for (key in data.form) {
				var element = document.getElementById('form_'+key);
				if (element) {
					if (data.form[key]) {
						element.value = data.form[key];
					} else {
						element.value = '';
					}
				};
			}
		}
		if (data.pos_error) {
			for (key in data.pos_error) {
				var element = document.getElementById('error_'+key);
				if (element) {
					element.innerHTML = data.pos_error[key];
				};
				element = document.getElementById('container_'+key);
				if (element) {
					if (data.pos_error[key]) {
						if (!element.className.match(/pos_error/)) {
							element.className = element.className+' pos_error';
						}
					} else {
						element.className = element.className.replace(/\s?pos_error/i, "");
					}
				}
			}
		}
	}
}

function linkGet (object) {
	$.get(object.href + '?content-type=application/json', {}, linkGetReply, 'json');
	return false;
}


function linkGetReply (data, textStatus) {
	if (data.status) {
		if (data.json_redirect) {location.replace(data.json_redirect); return false;};
		showMessage( "Ok get" );
	}
}

function text_limit_msg() {
    var counter = $('span[class=text-length]', $(this).closest('form'));
    var count=$(this).attr('maxlength');
    var a=$(this).val().length;
    if (a>count) {
        $(this).val( $(this).val().substring(0,count) );
        a=$(this).val().length;
    }
    if (counter.length) counter.text('(Осталось: '+(count-a)+')');
    return true;
}

function readMessageGet (object) {
	$.get(object.href + '?content-type=application/json', {}, readMessageGetReply, 'json');
	return false;
}

function readMessageGetReply (data, textStatus) {
	if (data.status) {
		if (data.json_redirect) {location.replace(data.json_redirect); return false;};
		$('#msg-'+data.form.id).removeClass('new');
		$('#msg-'+data.form.id).next().remove();
	}
}

var currentTooltip=null;
function show_tooltip (c,g) {
  function b () {
      return( document.documentElement && document.documentElement.scrollTop ) || ( document.body && document.body.scrollTop )
  }
  if(currentTooltip) {
    currentTooltip.remove();
    currentTooltip=null
  } else {
    if(g=="close"){return}
    var k=$("i:last",c).clone(), i=$("img",c), e=i.height();
    k.css({display:"block",visibility:"hidden"});
    $("body").append(k);
    currentTooltip=k;
    var h=$(i).offset().left, f=$(i).offset().top;
    var j=currentTooltip.width(),d=currentTooltip.outerHeight();
    openPositionX=h;
    if((h-j)>0){
      openPositionX=h-j
    }
    var a=3;
    openPositionY=f-d-a;
    if($(window).height()>(f+e+a+d-b())){
      openPositionY=f+e+a
    }
    $(currentTooltip).css({
      left:openPositionX+"px",top:openPositionY+"px",visibility:"visible"
    })
  }
}

function youTubeVideo() {
    var videoDivID = $(this).attr('id');
    if (videoDivID) {
        var videoID = videoDivID.split('---')[0];
        var params = { allowScriptAccess: "always" };
        var atts = { id: "ytPlayer-" + videoDivID };
        swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "&enablejsapi=1&playerapiid=player1",
                           videoDivID, "480", "295", "8", null, null, params, atts);

    }
}
function initSubscribeAnchor(obj) {
    obj.text(obj.attr('class')=="subscribe"?"Подписаться на уведомления о новых комментариях":"Отписаться от уведомлений о новых комментариях");
}
function deleteCommentResult (data, textStatus) {
    if (data.status) {
        if (data.html) {
            $('#comment-'+data.form.id).replaceWith($(data.html));
        } else {
            $('#comment-'+data.form.id).remove();
            if ($('.comments .comment').length < 1) {
                $('.comments h3.title').hide();
            }
        }
    }
}
function restoreCommentResult(data, textStatus) {
    if (data.status) {
        if (data.html) {
            $('#comment-'+data.form.id).replaceWith($(data.html));
        }
    }
}
function likeCommentResult (data, textStatus) {
    if (data.status) {
        $('#comment-'+data.form.id+' a.like').replaceWith('<span class="'+(data.form.vote == 'like' ? 's' : '')+'like rating-ico">↑</span>');
        $('#comment-'+data.form.id+' a.dislike').replaceWith('<span class="'+(data.form.vote == 'dislike' ? 's' : '')+'dislike rating-ico">↓</span>');
        $('#comment-'+data.form.id+' span.comment-rating').text(data.form.rating || '');
        $('#comment-'+data.form.id+' span.comment-rating').removeClass('green').removeClass('red');;
        $('#comment-'+data.form.id+' span.comment-rating').addClass(data.form.rating > 0 ? 'green' : 'red');
    }
}
function subscribeTreadResult(data, textStatus) {
    if (data.status) {
        $('div.comments div.subscribe a').removeClass();
        $('div.comments div.subscribe a').addClass(data.form.send_mail?"unsubscribe":"subscribe");
        initSubscribeAnchor($('div.comments div.subscribe a'));
        return false;
    }
}
function addCommentResult(data, textStatus) {
    if (data.status) {
        if (data.pos_error) {
            $('form .pos_error').text(data.pos_error.message);
        } else {
            $('form .pos_error').text('');
            $('div.comments').append(data.html);
            $('form.comment-form textarea').val('').each(text_limit_msg);
            if ($('.comments .comment').length > 0) {
                $('.comments h3.title').show();
            }
            if (data.form && data.form.send_mail) {
                subscribeTreadResult(data, textStatus);
            }
        }
    }
}
function updateMessages(data, textStatus) {
    if (data.html && data.html.length) {
        var ids = [];
        $('#messagelist .mailmessage').each(function(e,v) {
            ids.push($(this).attr('id').split('-')[1]);
        });
        for (var i=0;i<data.html.length;i++) {
            if (ids.length) {
                if (data.html[i].id < ids[0]) {
                    $('#messagelist #message-'+ids[0]).before($(data.html[i].html));
                    ids.unshift(data.html[i].id);
                } else {
                    for (var j=ids.length-1;j>=0;j--) {
                        var k = ids[j];
                        if (data.html[i].id == k) { break };
                        if (data.html[i].id > k) {
                            $('#messagelist #message-'+k).after($(data.html[i].html));
                            ids.splice(k+1, 0, data.html[i].id);
                            break;
                        }
                    }
                }
            } else {
                /*first*/
                $('#messagelist').append($(data.html[i].html));
                ids.unshift(data.html[i].id);
            }
            $("#messagelist #message-"+data.html[i].id+" span[class*=yt-object]").each(youTubeVideo);
        }
    }
}

if (window['jQuery']) {
    $(document).ready(function(){
        $('textarea[maxlength]').each(text_limit_msg).live('keyup', text_limit_msg);
        $('div.comment a.delete').live('click', function(){
            var id = $(this).attr('href').split('-')[1];
            $('#comment-'+id).addClass('comment-inremove');
            $.post( '/comments/actions/'+id+'/delete?content-type=application/json', {}, deleteCommentResult, 'json');
            return false;
        });
        $('div.comment .comment-actions a.like').live('click', function(){
            var id = $(this).attr('href').split('-')[1];
            $.post( '/comments/actions/'+id+'/like?content-type=application/json', {"like":"1"}, likeCommentResult, 'json');
            return false;
        });
        $('div.comment .comment-actions a.dislike').live('click', function(){
            var id = $(this).attr('href').split('-')[1];
            $.post( '/comments/actions/'+id+'/like?content-type=application/json', {"dislike":"1"}, likeCommentResult, 'json');
            return false;
        });        initSubscribeAnchor($('div.comments div.subscribe a'));
        $('form.comment-form').submit(function(){
            var qString = $(this).formSerialize();
            if ($('textarea[name=message]', $(this)).val().length > 1) {
                $.post( this.action + '?content-type=application/json', qString, addCommentResult, 'json');
            }
            return false;
        });
        $('div.comments div.subscribe a').live('click', function(){
            var id = $('div.comments div.subscribe').attr('name');
            $.post( '/comments/'+id+'/subscribe'+'?content-type=application/json', {"yes": ($(this).attr('class')=="subscribe"?"1":"0")}, subscribeTreadResult, 'json');
            return false;
        });
        $("span[class*=yt-object]").each(youTubeVideo);
        /*Control of images*/
        $('img.ctrl-img').each(function() {
            var maxWidth = 650; // Max width for the image
            var maxHeight = 1000;    // Max height for the image
            var ratio = 0;  // Used for aspect ratio
            var width = $(this).width();    // Current image width
            var height = $(this).height();  // Current image height

            // Check if the current width is larger than the max
            if(width > maxWidth){
                ratio = maxWidth / width;   // get ratio for scaling image
                $(this).css("width", maxWidth); // Set new width
                $(this).css("height", height * ratio);  // Scale height based on ratio
                height = height * ratio;    // Reset height to match scaled image
            }

            // Check if current height is larger than max
            if(height > maxHeight){
                width = $(this).width();    // Current image width
                ratio = maxHeight / height; // get ratio for scaling image
                $(this).css("height", maxHeight);   // Set new height
                $(this).css("width", width * ratio);    // Scale width based on ratio
                width = width * ratio;    // Reset width to match scaled image
            }
        });
        $("i[class=helper]").mouseout( function(){show_tooltip(this,'close')} ).mouseover( function(){show_tooltip(this,'')} );
        $('input[class*=suggest-citizenship]').autocomplete("/suggest/common/citizenship", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
               var array = new Array();
               for(var i=0;i<data.items.length;i++)
               {
                   array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
               }
               return array;
            },
            formatItem: function(row) {
               return row.value;
            }
        });
        $('input[class*=suggest-city]').autocomplete("/suggest/location", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: true,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            onListShow: function(container) { container.bgiframe(); },
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value.split(" (")[0] };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        }).result(function(event, data, formatted) {
            $(this).next().val( data ? data.id : '' );
        }).blur(function(){
            $(this).search();
        });
        $('input[class*=suggest-actor_valais_name]').autocomplete("/suggest/common/actor_valais", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-sport]').autocomplete("/suggest/common/sport", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            multiple: true,
            multipleSeparator: ", ",
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-music]').autocomplete("/suggest/common/music", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            multiple: true,
            multipleSeparator: ", ",
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-vocal]').autocomplete("/suggest/common/vocal", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            multiple: true,
            multipleSeparator: ", ",
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-dance]').autocomplete("/suggest/common/dance", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            multiple: true,
            multipleSeparator: ", ",
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-education_faculty]').autocomplete("/suggest/common/education_faculty", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
               var array = new Array();
               for(var i=0;i<data.items.length;i++)
               {
                   array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
               }
               return array;
            },
            formatItem: function(row) {
               return row.value;
            }
        });
        $('input[class*=suggest-education_specialty]').autocomplete("/suggest/common/education_specialty", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
               var array = new Array();
               for(var i=0;i<data.items.length;i++)
               {
                   array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
               }
               return array;
            },
            formatItem: function(row) {
               return row.value;
            }
        });
        $('input[class*=suggest-position]').autocomplete("/suggest/common/experience_position", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                    return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('input[class*=suggest-project]').autocomplete("/suggest/common/experience_project", {
            minChars: 2,
            width: 310,
            dataType: 'json',
            mustMatch: false,
            matchContains: "word",
            autoFill: false,
            deferRequestBy: 100,
            parse: function(data) {
                var array = new Array();
                for(var i=0;i<data.items.length;i++)
                {
                    array[array.length] = { data: data.items[i], value: data.items[i].value, result: data.items[i].value };
                }
                return array;
            },
            formatItem: function(row) {
                return row.value;
            }
        });
        $('a.rndpage').attr('href', $('a.rndpage').attr('href')+'?page='+Math.round(Math.random()*240));
		$('textarea.autosubmit').keypress(function(event){
			if ((event.ctrlKey && (event.keyCode==10||event.keyCode==13))) {
				$(this).parents('form').submit();
			}
		});

    });
}


