var CURRENT_PAGE = window.location.href;
var addthis_config = {ui_click: true}
var myGallery;
var galleryInstant = false;

$(document).ready(function(){
    initDropDownActions();
    initLastAdsActions();
    initMapActions();
    $('input[title!=""]').hint();
    //$(window).resize(resizeHandler);
    positionBaseline();
    if($('#myGallery').length){ myGallery = new ImageFlow(); }
    //resizeHandler();
});

//window.onload = onloadHandler;
//function onloadHandler(){
//    resizeHandler();
//}
//
//function resizeHandler(){
//
//}.greece_map

function changeLang(lang){
	createCookie('hvh_language',lang);
	window.location.reload();
}

function initMapActions(){
    $('.greece_map a').mouseover(function() {
        showTooltip($(this).attr('rel'));
    }).mouseout(function(){
        hideTooltip();
    });
    $('.attica_map a').mouseover(function() {
        showTooltip($(this).attr('rel'));
    }).mouseout(function(){
        hideTooltip();
    });
}

function initDropDownActions(){
    $('.mainbtn').mouseenter(function() {
        $(this).find(".dropdown_menu").show();
    }).mouseleave(function() {
        $(this).find(".dropdown_menu").hide();
    });

    $('.subbtn').mouseenter(function() {
        $(this).find(".dropdown_submenu").show();
    }).mouseleave(function() {
        $(this).find(".dropdown_submenu").hide();
    });
}

function initLastAdsActions(){
    $('.last_item').mouseenter(function() {
        id = $(this).attr('id');
        $('#back'+id).fadeTo(200, 0.7);
        $('#info'+id).fadeTo(200, 1);
    }).mouseleave(function() {
        id = $(this).attr('id');
        $('#back'+id).fadeTo(200, 0);
        $('#info'+id).fadeTo(200, 0);
    });
}

function positionBaseline(){
    if(!$('#baseline').hasClass('closed')){
        $('#baseline').addClass('opened');
        var bottom =$('.baseline_contents').height()-5;
        $('#baseline').css({"bottom":bottom+"px"});
    }
}

function selectContract(str){
    $('.optionsbox .contract_cont').each(function(){
        $(this).find('.contract_input').val(str);
        if(str == 'for_sale' && $(this).find('.for_rent').hasClass('selected')){$(this).find('.for_rent').removeClass('selected');}
        if(str == 'for_rent' && $(this).find('.for_sale').hasClass('selected')){$(this).find('.for_sale').removeClass('selected');}
        if(!$(this).find('.'+str).hasClass('selected')){$(this).find('.'+str).addClass('selected');}
    });    
}

function submitFindCode(dv){
  if($('#searchInput').val()!=dv && $('#searchInput').val().length){
    $('#codesearch').submit();
  }
}

function checkEnter(e){
  var characterCode;
  if(e && e.which){
      e = e;
      characterCode = e.which;
  }else{
      e = event;
      characterCode = e.keyCode;
  }
  if(characterCode == 13){return true;}
  else{return false;}
}

function checkSearchEnter(e, dv){
  if(checkEnter(e)){
    submitFindCode(dv);
  }
}

function changeSubType(id){
    $('.sub_type_select').each(function(){
        $(this).slideUp();
    });
    $('#subselect_'+id).slideDown();
}

function setSubType(id){  $('#subtype_input').val(id); }

function showPhoto(id){
    if($('#player'+id).length){
        jwplayer('player'+id).stop();
        $('#player_btn'+id).removeClass('selected');
        $('#player'+id).hide();
    }
    if(myGallery){}else{ myGallery = new ImageFlow(); }
    $('#photos'+id).show();
    $('#photos_btn'+id).addClass('selected');
    if(!galleryInstant){
        if(!('#player'+id).length){
            myGallery.init({ ImageFlowID: 'myGallery', captions: true, reflections: false, reflectionP: 0.0, slider: false, aspectRatio: 1.618, imagesHeight:0.95, imageFocusM:2.3, slideshow: true, slideshowAutoplay: true });
        }else{
            myGallery.init({ ImageFlowID: 'myGallery', captions: true, reflections: false, reflectionP: 0.0, slider: false, aspectRatio: 1.618, imagesHeight:0.9, imageFocusM:2.2});
        }
    }
    galleryInstant = true;
    //slideShow('selected');
}

function showVideo(id){
    jwplayer('player'+id).play();
    $('#photos'+id).hide();
    $('#player'+id).show();
    $('#player_btn'+id).addClass('selected');
    $('#photos_btn'+id).removeClass('selected');
}

function showColorImage(str){ $.colorbox({href:str}); }


function showShop(){
    $('#shopProducts').hide();
    $('#shopVideo').show();
    $('#shop_btn').addClass('selected');
    $('#products_btn').removeClass('selected');
}

function showProducts(){
    $('#shopProducts').show();
    $('#shopVideo').hide();
    jwplayer('shopPlayer').stop();
    $('#shop_btn').removeClass('selected');
    $('#products_btn').addClass('selected');
}

function switchProduct(num){
    if($('#shop_btn').length && $('#shop_btn').hasClass('selected')){ showProducts(); }
    var $active = $('.slideitem.active');
    var next = $('#shopProducts .slideitem').get(num);
    $active.removeClass('active');
    $active.hide();
    $(next).fadeIn();
    $(next).addClass('active');
}

function submitAdEmail(){
    if(checkInput("#firstname") && checkInput("#lastname") && checkInput("#email") && checkInput("#phone")){
        if(!validEmail($("#email").val())){ showError('To email που καταχωρήσατε δεν είναι αποδεκτό!');}
        else{$('#contactform').submit();}
    }else{ showError('Παρακαλούμε εισάγετε όλα τα πεδία!'); }
}

function submitShopEmail(){
    if(checkInput("#firstShopname") && checkInput("#shopemail")){
        if(!validEmail($("#shopemail").val())){ alert('To email που καταχωρήσατε δεν είναι αποδεκτό!');}
        else{$('#contactShopform').submit();}
    }else{ alert('Παρακαλούμε εισάγετε όλα τα πεδία!'); }
}

function submitLoginByEmail(){
    if(checkInput("#email_login") && checkInput("#password_login")){
        if(!validEmail($("#email_login").val())){
            $('#loginerror').html('To email που καταχωρήσατε δεν είναι αποδεκτό!');
            setTimeout("$('#loginerror').html('');", 4000);
        }else{$('#loginform').submit();}
    }else{
        $('#loginerror').html('Παρακαλούμε εισάγετε όλα τα πεδία!');
        setTimeout("$('#loginerror').html('');", 4000);
    }
}

function submitLogin(){
    if(checkInput("#username_login") && checkInput("#password_login")){
        $('#loginform').submit();
    }else{
        $('#loginerror').html('Παρακαλούμε εισάγετε όλα τα πεδία!');
        setTimeout("$('#loginerror').html('');", 4000);
    }
}

function submitForgot(){
    if(checkInput("#email_forgot")){
        if(!validEmail($("#email_forgot").val())){
            $('#loginerror').html('To email που καταχωρήσατε δεν είναι αποδεκτό!');
            setTimeout("$('#loginerror').html('');", 4000);
        }else{$('#forgotform').submit();}
    }else{
        $('#loginerror').html('Παρακαλούμε εισάγετε το email σας!');
        setTimeout("$('#loginerror').html('');", 4000);
    }
}

function toggleForgot(){
    if($('#login_forgot').is(':hidden')){
        $('#login_forgot').show();
        $('#login_inside').hide();
    }else{
        $('#login_forgot').hide();
        $('#login_inside').show();
    }
}


function submitContact(id){
    if(checkInput("#"+id+" .firstname") && checkInput("#"+id+" .lastname") && checkInput("#"+id+" .email")){
        if(!validEmail($("#"+id+" .email").val())){            
            $('#'+id+' .error').html('To email που καταχωρήσατε δεν είναι αποδεκτό!');
            setTimeout("$('#"+id+" .error').html('');", 4000);
            return;
        }
        if(id == 'userform' && !$('#is_realtor').is(':checked') && !$('#is_proffesional').is(':checked')){
            $('#'+id+' .error').html('Παρακαλούμε επιλέξτε εάν είστε μεσίτης ή επαγγελματίας!');
            setTimeout("$('#"+id+" .error').html('');", 4000);
            return;
        }
        $('#'+id).submit();
    }else{
        $('#'+id+' .error').html('Παρακαλούμε εισάγετε όλα τα πεδία!');
        setTimeout("$('#"+id+" .error').html('');", 4000);
    }
}


function submitEntrustment(){
    if(checkInput(".firstname") && checkInput(".lastname") && checkInput(".phone") && checkInput(".email")
		&& checkInput(".region") && checkInput(".category") && checkInput(".purpose")
	){
        if(!validEmail($(".email").val())){            
            $('.error').html('To email που καταχωρήσατε δεν είναι αποδεκτό!');
            setTimeout("$('.error').html('');", 4000);
            return;
        }
		$('#entrustment_clear').attr('value', '1');
        $('#entrustmentform').submit();
    }else{
        $('.error').html('Παρακαλούμε εισάγετε όλα τα πεδία με τον αστερίσκο!');
        setTimeout("$('.error').html('');", 4000);
    }
}


function slideShow(dir){
    var $active = $('.slide_imgcont.selected');
    var $next;
    if(dir == 'next' && $active.next('.slide_imgcont').length){
        $next = $active.next('.slide_imgcont');
    }else if(dir == 'prev' && $active.prev('.slide_imgcont').length){
        $next = $active.prev('.slide_imgcont');
    }else if(dir == 'selected'){ $next = $active; }
    if($next){
        var X = $next.position().left - $('#slideshow_inside').position().left + (($next.width()-600)*0.5);
        $('#slideshow_container').animate({scrollLeft: X}, 400);
        $active.removeClass('selected');
        $next.addClass('selected');
        if(!$next.next('.slide_imgcont').length){
            $('.slide_right_arrow').addClass('disabled');
        }else if($('.slide_right_arrow').hasClass('disabled')){$('.slide_right_arrow').removeClass('disabled');}
        if(!$next.prev('.slide_imgcont').length){
            $('.slide_left_arrow').addClass('disabled');
        }else if($('.slide_left_arrow').hasClass('disabled')){$('.slide_left_arrow').removeClass('disabled');}
    }
}

function checkInput(el){
    if(!$(el).val().length || $(el).val() == $(el).attr('title')){return false;}
    else{return true;}
}

function showError(txt, hide){
    $('.error').html(txt);
    if(!hide){setTimeout("$('.error').html('');", 4000);}
}

function validEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}

function showAtticaMap() {
    $('.map_tooltip .selected').addClass('hidden');
    $('.map_tooltip .selected').hide();
    $('.map_tooltip .selected').removeClass('selected');
    $('#region_title_3').show();
    $('#region_title_3').addClass('selected');
    $('#region_title_3').removeClass('hidden');
    $('.greece_map').hide();
    $('.attica_map').fadeIn();
}

function showTooltip(id) {
    $('.map_tooltip .selected').hide();
    $('#region_title_'+id).show();
}

function hideTooltip() {
    $('.map_tooltip .hidden').hide();
    $('.map_tooltip .selected').show();
}

jQuery.fn.hint = function (blurClass) {
    if (!blurClass) {
        blurClass = 'blur';
    }
    return this.each(function () {
        var $input = jQuery(this),
        title = $input.attr('title'),
        $form = jQuery(this.form),
        $win = jQuery(window);
        function remove(){
            if ($input.val() === title && $input.hasClass(blurClass)) {
                $input.val('').removeClass(blurClass);
            }
        }
    if (title) {
        $input.blur(function(){
            if (this.value === '') {
                $input.val(title).addClass(blurClass);
            }
        }).focus(remove).blur();
        $form.submit(remove);
        $win.unload(remove);
    }
});
};

function toggleBaseline(){
    if($('#baseline').hasClass('closed')){
        $('#baseline').removeClass('closed');
        $('#baseline').addClass('opened');
        var bottom =$('.baseline_contents').height()-5;
        $('#baseline').animate({"bottom":bottom+"px"}, 500);
    }else{
        $('#baseline').removeClass('opened');
        $('#baseline').addClass('closed');
        if($('#baseline').hasClass('connected')){$('#baseline').animate({"bottom":"25px"}, 500);}
        else{$('#baseline').animate({"bottom":"0px"}, 500);}
    }
}

function editSection(nm){
    $('.profile_error').html('');
    section = nm+'_cont';
    $('.profile_menu a').removeClass('opened');
    if($('.'+section).hasClass('hidden')){
        $('.'+nm+'_btn').addClass('opened');
        if($('.new_post_cont').length && !$('.new_post_cont').hasClass('hidden')){$('.new_post_cont').addClass('hidden');}
        if($('.view_posts_cont').length && !$('.view_posts_cont').hasClass('hidden')){$('.view_posts_cont').addClass('hidden');}
        if($('.edit_profile_cont').length && !$('.edit_profile_cont').hasClass('hidden')){$('.edit_profile_cont').addClass('hidden');}
        if($('.edit_post_cont').length && !$('.edit_post_cont').hasClass('hidden')){$('.edit_post_cont').addClass('hidden');}
        $('.'+section).removeClass('hidden');
        if($('#baseline').hasClass('closed')){toggleBaseline();}
        else{
            var bottom =$('.baseline_contents').height()-5;
            $('#baseline').animate({"bottom":bottom+"px"}, 500);
        }
    }else{
        $('#baseline').animate({"bottom":"25px"}, 500, function(){ $('.'+section).addClass('hidden'); });
    }
}

function focusSection(nm){
    section = nm+'_cont';
    $('.profile_menu a').removeClass('opened');
    if($('.'+nm+'_btn').length){$('.'+nm+'_btn').addClass('opened');}
    $('.'+section).removeClass('hidden');
    $('#baseline').removeClass('closed');
    $('#baseline').addClass('opened');
    var bottom =$('.baseline_contents').height()-5;
    $('#baseline').css({"bottom":bottom+"px"});
}

function changeSubEditType(id){
    $('.sub_edit_type_select').each(function(){
        $(this).slideUp();
    });
    $('#subEditSelect_'+id).slideDown();
}

function submitNewAdd(){
    if(checkInput("#addPostForm #new_title") && checkInput("#addPostForm #new_code") && ($("#addPostForm #for_sale").is(':checked') || $("#addPostForm #for_rent").is(':checked')) ){
       $('#addPostForm').submit();
    }else{ $(".profile_inputs .message").css({'background':'#f00', 'color':'#fff'}); }
}

function submitUpdateAdd(){
    if(checkInput("#new_title") && checkInput("#new_code") && ($("#for_sale").is(':checked') || $("#for_rent").is(':checked')) ){
       $('#editPostForm').submit();
    }else{ $(".profile_inputs .message").css({'background':'#f00', 'color':'#fff'}); }
}

function submitNewProduct(){
    if(checkInput("#addProductForm #new_title") && checkInput("#addProductForm #new_text") && checkInput("#addProductForm #new_product")){
       $('#addProductForm').submit();
    }else{
        $(".profile_error").html('<span class="round">Παρακαλούμε εισάγετε όλα τα πεδία!</span>');
        setTimeout("$('.profile_error').html('');", 7000);
    }
}

function submitEditProduct(){
    if(checkInput("#editProductForm #new_title") && checkInput("#editProductForm #new_text")){
       $('#editProductForm').submit();
    }else{
        $(".profile_error").html('<span class="round">Παρακαλούμε εισάγετε όλα τα πεδία!</span>');
        setTimeout("$('.profile_error').html('');", 7000);
    }
}

function deleteMedia($id){
    $.ajax({
        type: "POST",
        url: baseURL+'users/delete_media',
        data: ({id: $id}),
        success: function(msg){
            $('#media_'+$id).fadeOut(400, function(){ window.location.reload(); });
        },
        error:function (xhr, ajaxOptions, thrownError){console.log('ajaxError: '+xhr+' '+ajaxOptions+' '+thrownError);}
    });
}

function deleteTopic($id){
    if (confirm("Είστε σίγουροι οτι θέλετε να διαγράψετε την αγγελία;")) {
        $.ajax({
            type: "POST",
            url: baseURL+'ads/delete_topic',
            data: ({id: $id}),
            success: function(msg){
                window.location = baseURL;
            },
            error:function (xhr, ajaxOptions, thrownError){console.log('ajaxError: '+xhr+' '+ajaxOptions+' '+thrownError);}
        });
    }
}

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

