jQuery(document).ready(function(){
  if(jQuery('.customselector').length > 0) jQuery('.customselector').customSelect();
  
//   jQuery("a[@href*='/login']").each(function() {
//     this.href = this.href.replace(/user\/login(%3F|\?)?/,"user/login/ajaxlogin?height=230&width=415&")
//   });
    
  jQuery("a[@href*='/login']").click(function(){
    jQuery(this).login_ajax_content();
    return false;
  });
  jQuery('a[rel=showimage]').click(function(){
    showThickbox(this.href, 'image');
    return false;
  });
  jQuery('a[@rel=showtext]').click(function() {
    showThickbox(this.href, 'textbox');
    return false;
  }); 
  jQuery('a[@rel=showhtml]').click(function() {
    showThickbox($(this).next('.thickbox-html-content').html(), 'html');
    return false;
  });
  
  
  jQuery("#menu_front_page .head_menu, #searchresult .head_menu.link").hover(
    function () {
      $(this).addClass(($(this).hasClass('locale-th') ? 'hover-th' : 'hover-en'));
    }, 
    function () {
      $(this).removeClass(($(this).hasClass('locale-th') ? 'hover-th' : 'hover-en'));
    }
  );
});

jQuery.fn.login_ajax_content = function() {
  var destination=false;
  var target=false;
  var href = $(this).attr("href");
  var pattern = /destination=(.*)/
  if(href) {
    var dest = href.match(pattern) ? href.match(pattern)[1] : '';
    if(dest != '') destination = dest;
    target = $(this).attr("target") ? $(this).attr("target") : false;
  }

  var focus_blur_event = 'onfocus="document.onkeydown=\'return true\'; document.onkeypress=\'return true\';" onblur="hide_thickbox=true; if(typeof mmmap !=\'undefined\') mmmap.setKeyFocusAtMaparea();"';

  var login_html = '<div class="tabs" style="margin-top:0px">'
+'  <ul id="ajax-login" class="tabs primary" style="display:inline;">'
+'    <li class="active">'
+'      <a class="active">Log in</a>'
+'    </li>'
+'    <li>'
+'      <a href="/login/user" style="position:relative;">Create new account</a>'
+'    </li>'
+'    <li>'
+'      <a href="/login/password" style="position:relative;">Request new password</a>'
+'    </li>'
+'  </ul>'
+'</div>'
+'<form id="longdologin-form-ajax" onsubmit="login_ajax(\''+destination+'\',\''+target+'\');" action="javascript:void(0);" style="text-align:left;">'
+'  <div style="text-align:left;">'
+'    <div class="form-item">'
+'      <label for="username-ajax">username: </label>'
+'      <input '+focus_blur_event+' id="username-ajax" class="form-text" type="text" tabindex="1" value="" size="60" name="username" maxlength="128" rel="thickbox-focus">'
+'      <div class="description">Enter your longdo.com username.</div>'
+'    </div>'
+'    <div class="form-item">'
+'      <label for="pass-ajax">password: </label>'
+'      <input '+focus_blur_event+' id="pass-ajax" class="form-text" type="password" tabindex="2" size="60" name="pass"/>'
+'      <div class="description">Enter the password that accompanies your username.</div>'
+'    </div>'
+'    <input id="login-submit-ajax" class="form-submit" type="submit" tabindex="3" value="เข้าสู่ระบบ" name="op"/>'
+'  </div>'
+'</form>'
+'<div id="login-loading" style="text-align:center; display:none;"><img src="/mmmap/images/loading.gif" style="margin-top:30px;"></div>';
    showThickbox(login_html, 'html');
    return false;
}

function login_ajax(destination, target) {
  var username_val = '';
  var password_val = '';
  if($('#username-ajax')) username_val = $('#username-ajax').val();
  if($('#pass-ajax')) password_val = $('#pass-ajax').val();
  var alerttxt = username_val != '' ? (password_val != '' ? "" : "Password is required.") : (password_val != '' ? "Username is required." : "Username and Password are required.") ;
  if(alerttxt != '') { alert(alerttxt); return;}
  
  $('#login-loading').css('display','inline');
  $('#longdologin-form-ajax').css('display','none');
  $('#login-error-txt').remove();
  
  //$('#loginform-loading').show();
  $.ajax({
    type: 'POST',
    cache: false,
    url: 'longdo_login_submit',
    data: ({
      'username' : $('#username-ajax').val(),
      'password' : $('#pass-ajax').val()
    }),
    success: function(output) {
      var js_command = eval(output);
      if (user_id == 0) {
        $('#login-loading').css('display','none');
        var errortxt = mylang=="en" ? "* The username or pasword is incorrect. Please try again." :
          "* Username หรือ password ผิด โปรดลองใหม่อีกครั้ง";
        $('#longdologin-form-ajax').css('display','inline');
        $('#longdologin-form-ajax').prepend('<div id="login-error-txt" style="color:red; font-size:11px; text-align:right; margin-bottom:-13px; margin-top:3px;">'+errortxt+'</div>');
      }    
      else if (user_id == -1) {
        $('#login-loading').css('display','none');
        var errortxt = mylang=="en" ? "* Longdo.COM is not available right now. Please try again later." :
          "* Longdo.COM อยู่ในระหว่างการพัฒนาระบบ กรุณาลองใหม่ภายหลัง";
        $('#longdologin-form-ajax').css('display','inline');
        $('#longdologin-form-ajax').prepend('<div id="login-error-txt" style="color:red; font-size:11px; text-align:right; margin-bottom:-13px; margin-top:3px;">'+errortxt+'</div>');
      }
      else {
        if($('#longdotab').length > 0) {
          var tabs = $('#longdotab > ul').tabs();
          var selectedIndex = tabs.tabs('option', 'selected');
          if(selectedIndex > 0) {
            var selectedTab = $('#longdotab > ul > li.ui-tabs-selected');
            var selectedTabTitle = $('#longdotab > ul > li.ui-tabs-selected > span.span-tab > a > span').html();
            var selectedTabID = $('#longdotab > ul > li.ui-tabs-selected > span.span-tab > a').attr('href');
            selectedTabID = selectedTabID.replace(/^#|-[0-9]+$/g, "");
            selectedTabID = selectedTabID.replace(/\_/g, "/");
  
            $.cookie("longdotab_id_path_tab", selectedTabID);
            $.cookie("longdotab_title_tab", selectedTabTitle);
          }
        }
        
        if(destination != 'false') destination = '/'+decodeURIComponent(decodeURIComponent(String(destination).replace(/\+/g, '%20')));
        if(destination != 'false' && destination != window.location.pathname) {
          if(target == '_blank') {
            window.location.reload();
            window.open(destination);
          }
          else window.location=destination;
        }
        else window.location.reload();
      }      
    }
  }); 
}

function showLargeImage() {
  jQuery("a#show-large-image").css('display','none');
  jQuery("a#show-thumbnail-image").css('display','inline');
  
  jQuery("#image-related a img").each(function(){
    jQuery(this).css('display','none');
    jQuery(this).attr('src', jQuery(this).parent("a").attr("href"));
    
    jQuery(this).load(function() {  
      if(this.width > 630) {
        jQuery(this).css("width","630px");
      }
      jQuery(this).css('display','inline');
    });
  })
}

function showThumbnailImage() {
  jQuery("a#show-thumbnail-image").css('display','none');
  jQuery("a#show-large-image").css('display','inline');
  
  jQuery("#image-related a img").each(function(){
    jQuery(this).attr('src','drupal-nodes-backup/create_square_thumb.php?img=' + jQuery(this).attr('src') + '&size=120');
    jQuery(this).css({ width: "", display: "inline" }); // Remove css dimensions as well
  })
}

var hide_thickbox = true;

function showThickbox(text, format) {
  hideThickbox();
  jQuery('#imageviewholder').attr('class', 'imageviewholderloading');
  
  var close_button = '<div id="closethickbox" style="right:3px; top:3px; cursor:pointer; position:absolute;"><img title="close" src="/mmmap/images/cross-red.png"></div>';
  
  var content = '';
  if(format=='textbox') content = '<span id="imageview" style="display:none;">'+close_button+'<div style="text-align:left;font-size:10px;padding:5pxs 5px 0;color:#474747;">Copy text using Ctrl+C</div><input rel="thickbox-focus" onclick="hide_thickbox=false;" onblur="hide_thickbox=true;" style="width:250px; margin:5px;" type=text value="' + text + '"></span>';
  else if(format=='image') content = '<div style="display:none;" id="imageview">'+close_button+'<img class="show-this-image" src="' + text + '"></div>';
  else if(format=='html') content = '<div id="imageview" style="display:none;" onclick="hide_thickbox=false;" onblur="hide_thickbox=true;">' + close_button + '<div style="padding:10px;">' + text + '</div></div>';
    
  jQuery('#imageviewholder').html(content);
  
  jQuery('#imageviewholder').fadeIn(200);
  jQuery('#imageviewbg').fadeIn(300);
  
  if(format=='image') {
    jQuery('#imageview img.show-this-image').load(function() {
      adjustThickbox();
    });
  }
  else {
    setTimeout('adjustThickbox()', 300);
  }
  
  jQuery('#imageviewholder').click(hideThickbox);
  jQuery('#closethickbox').click(function(){hideThickbox('hide');});
  jQuery(document).keydown(function(event) {
    if (event.keyCode == '27' && jQuery('#imageviewholder') && jQuery('#imageviewholder').css('display')=='block') {
      hideThickbox('hide');
    }
  });
}

function hideThickbox(hide) {
  if(hide_thickbox || hide=='hide') {
    $('#imageviewholder').empty();
    $('#imageviewholder').hide();
    $('#imageviewbg').hide();
  }
}

function adjustThickbox() {  
  var imageView = jQuery('#imageview, #imageview img.show-this-image');
  var image = jQuery('#imageview img.show-this-image');
  
  imageView.fadeIn('fast');
  
  jQuery("#imageview input[@rel='thickbox-focus']").focus();
  jQuery("#imageview input[@rel='thickbox-focus']").select();
  jQuery('#imageviewholder').attr('class', 'imageviewholdercomplete');
  
  var windowwidth = parseInt(jQuery(window).width());
  var windowheight = parseInt(jQuery(window).height());
  var imgwidth = image.length > 0 ? parseInt(image.width()) : parseInt(imageView.width());
  var imgheight = image.length > 0 ? parseInt(image.height()) : parseInt(imageView.height());

  if(windowwidth-imgwidth < windowheight-imgheight) {
    imageView.css('width', ((imgwidth+8)>windowwidth ? (windowwidth-8)+'px' : imgwidth+'px'));
  }
  else {
    imageView.css('height', ((imgheight+8)>windowheight ? (windowheight-8)+'px' : imgheight+'px'));
  }
  
  var imgwidth = image.length > 0 ? parseInt(image.width()) : parseInt(imageView.width());
  var imgheight = image.length > 0 ? parseInt(image.height()) : parseInt(imageView.height());
  
  if(image.length > 0) {
    image.css( {width:imgwidth, height:imgheight } );
  }
  
  imageView.css( {top:((imgheight+16) > windowheight ? 0 : (windowheight - imgheight - 16) / 2)+'px', left:((imgwidth+16) > windowwidth ? 0 : (windowwidth - imgwidth - 16) / 2)+'px' } );
}

function loadjscssfile(filename, filetype){
  if (filetype=="js"){ //if filename is a external JavaScript file
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", filename)
  }
  else if (filetype=="css"){ //if filename is an external CSS file
    var fileref=document.createElement("link")
    fileref.setAttribute("rel", "stylesheet")
    fileref.setAttribute("type", "text/css")
    fileref.setAttribute("href", filename)
  }
  if (typeof fileref!="undefined")
    document.getElementsByTagName("head")[0].appendChild(fileref);
}

var filesadded="" //list of files already added

function checkloadjscssfile(filename, filetype){
  if (filesadded.indexOf("["+filename+"]")==-1){
    loadjscssfile(filename, filetype)
    filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc"
  }
}

jQuery.fn.customSelect = function() {
  // define defaults and override with options, if available
  // by extending the default settings, we don't modify the argument
  return this.each(function() {
    var selected_obj = false; 
    obj = jQuery(this);
    obj.after("<div id=\"selectoptions\"></div>");
    obj.find('option').each(function(i) { 
      jQuery("#selectoptions").append("<div title=\""+jQuery(this).html()+"\" id=\"" + jQuery(this).attr("value") + "\" class=\"selectitems\"><img src=\"" + this.title + "\" /> <span class='select-text'>" + jQuery(this).html() + "</span></div>");
      if(jQuery(this).attr("value")==jQuery('.customselector').val()) {
        selected_obj = "<img src=\"" + this.title + "\" /> <div class='select-text'>" + jQuery(this).html() + "</div>";
      }
    });
    if(selected_obj) {
      obj.before("<input type=\"hidden\" value =\"\" name=\"" + this.name + "\" class=\"customselect\"/><div id=\"iconselect\">" + selected_obj + "</div><div id=\"iconselectholder\"> </div>").remove();
    }
    else {
      obj.before("<input type=\"hidden\" value =\"\" name=\"" + this.name + "\" class=\"customselect\"/><div id=\"iconselect\">" + this.title + "</div><div id=\"iconselectholder\"> </div>").remove();
    }
    jQuery("#iconselect .select-text").css( {width: jQuery('#iconselect').width()-(jQuery('#iconselect img').width()+28)+"px"} );
    jQuery("#iconselectholder").append( jQuery("#selectoptions")[0] );
    jQuery("#iconselect").click(function(){
      jQuery("#iconselectholder").css( {
        width: (jQuery('#pre-customselect').width()+jQuery('#iconselect').width()-2)+"px",
        left: "-"+(jQuery('#pre-customselect').width()+jQuery('#iconselect').width())+"px",
        top: jQuery('#iconselect').height()+1+"px"
      } );
      jQuery("#iconselectholder").toggle("fast");
    });
    jQuery(".selectitems").mouseover(function(){
    	jQuery(this).addClass("hoverclass");
    });
    jQuery(".selectitems").mouseout(function(){
    	jQuery(this).removeClass("hoverclass");
    });
    jQuery(".selectitems").click(function(){
    	jQuery(".selectedclass").removeClass("selectedclass");
    	jQuery(this).addClass("selectedclass");
    	var thisselection = jQuery(this).html();
    	thisselection.replace("<span", "<div'");
    	thisselection.replace("</span>", "</div>");
      jQuery(".customselect").val(this.id);
    	jQuery("#iconselect").html(thisselection);
    	jQuery("#iconselectholder").toggle("fast");
    	if(obj.hasClass('onchange-changeCategoryOOI')) {
        window.location = 'http://'+location.hostname+"/poilist/"+jQuery(".customselect").val()+"/recently";
      }
    });
  });  
}
