var js_append_dir = '';
var fancyoptions = {'frameWidth':480, 'frameHeight':260, 'overlayShow': true, 'overlayOpacity':0.9, 'hideOnContentClick': false, 'centerOnScroll':false,  'zoomOpacity': false, 'itemArray':new Array() };

if(window && window.location && window.location.href && window.location.href.indexOf('office.tvarwebu.cz') !== -1)
  js_append_dir = 'freetradeireland/';
var ireland_lat_north = 54.6; // 54.9
var ireland_lat_south = 51.7; // 51.4
var ireland_lng_east  = -6.1;
var ireland_lng_west  =-10.4;

$(document).ready(function() {
  $('.targetNew').attr('target', '_new');
  $('#account_type_selection input').click(function(){
    selected_item = $(this).attr('value');
    if(selected_item == 'business'){
      $('.showOnHousehold').slideUp();
      $('.showOnBusiness').slideDown();
      //$('#tr_logo').slideDown().fadeTo('slow',1);
      //$('#tr_website').slideDown().fadeTo('slow',1);
    }else{
      $('.showOnHousehold').slideDown();
      $('.showOnBusiness').slideUp();
      //$('#tr_logo').fadeTo('slow', 0.01).slideUp();
      //$('#tr_website').fadeTo('slow', 0.01).slideUp();
    }
  });
 $('#projectRequirements').click(function(){

  });
  $('.ajaxFancyBox').each(function(){
    $(this).fancybox(fancyoptions);
  });
  $('.show_item_email').bind('click', function(e){
    url = $(this).attr("href");
    $.get(url, {type: 'ajax'}, function (tjson) { // action: 'item_email', town_id: town_select.value
      if(typeof tjson.email != "undefined") {
        var new_item   = '<div class="final_email" style="display:none; float: left;">'+tjson.email+'</div>';
        $('#eml_content').append(new_item).find('div').slideDown();
      }
      if(typeof tjson.error != "undefined"){
        alert(tjson.error);
        var new_item   = '<div style="display:none; float: left;">'+tjson.error+'</div>';
        $('#eml_content').append(new_item).find('.final_email').slideDown();
      }
      $('#eml_content .waiting').slideUp();
    }, 'json');
    $(this).slideUp('slow', function(){
      $('#eml_content .waiting').css('float','none');
    });
    var waiting_item = '<div class="waiting" style="display:none; float: left;display: block;">Loading email ...</div>';
    $('#eml_content').append(waiting_item).find('.waiting').slideDown();
    //alert('fadfa');
    return false;
  });
});

function open_popup_quantify(displayDivId){
  //fancyoptions2 = {'frameWidth':480, 'frameHeight':260,'overlayOpacity':0.9, 'centerOnScroll':false,  'hideOnContentClick': false, 'zoomOpacity': false, 'itemArray':new Array()};
  $('<a href="#'+displayDivId+'">test</a>').fancybox(fancyoptions).click();
  return false;
}

function changeDimensionsWeights(subcategory){
  //alert(subcategory.value);
  if(subcategories_weights[subcategory.value])
    $("#weight").attr('value', subcategories_weights[subcategory.value]);
}

// LCD:Mark 29/12/2010 15:37 - Retrict sugested weight to > .5 && < 4 of Item Weight data
function checkDimensionsWeights(objRef) {
	var subcategory_value = $("#subcategory_id_edit").val();
	var subcategory_weight = (subcategories_weights[subcategory_value]) ? subcategories_weights[subcategory_value] : 0;
	var suggested_weight = $("#" + objRef.id).val();
	//
	if(suggested_weight > 0 && subcategory_weight) {
		var result =  Math.round(suggested_weight / subcategory_weight * 100) / 100;
		var val = 0;
		if(result >= 1 && result <=4) val =  Math.round((suggested_weight) * 100) / 100;// keep suggested when within this lower & upper threshold
		else if(result > 4) val = Math.round((subcategory_weight * 4) * 100) / 100; // restrict to 4x default weight
		else if(result < .5) val = Math.round((subcategory_weight / 2) * 100) / 100; // restrict to .5 of default weight
		else val = suggested_weight; // anything else (?) keep suggested
		$("#" + objRef.id).attr("value",val);
	} else {
		$("#" + objRef.id).attr("value",subcategories_weights[subcategory_value]);
	}
	//
}

function save_favourite_search(currentitem){
  var url = 'favourite_search.php?keywords='+$('#keywords_search').val();
  url += '&item_type='+$('#item_type_search').val();
  url += '&category_id='+ $('#category_id_search').val();
  url += '&subcategory_id='+ $('#subcategory_id_search').val();
  url += '&county_id='+ $('#county_id_search').val();
  url += '&town_id='+ $('#town_id_search').val();
  url += '&distance='+ $('#distance_search').val();
  url += '&wanted='+ ($('#wanted_search:checked').length);

  $('<a href="'+url+'">favourite search</a>').fancybox(fancyoptions).click();
  //console.log(url);
}

function update_rss_link(){
  //alert(create_url_from_search());
  //window.location.assign('rss.php?'+create_url_from_search());
  window.open('rss.php?'+create_url_from_search());
}

function create_url_from_search(){
  var url = 'keywords='+($('#keywords_search').val()!='Keywords' ? $('#keywords_search').val() : '');
  url += '&item_type='+$('#item_type_search').val();
  url += '&category_id='+ $('#category_id_search').val();
  url += '&subcategory_id='+ $('#subcategory_id_search').val();
  url += '&county_id='+ $('#county_id_search').val();
  url += '&town_id='+ $('#town_id_search').val();
  url += '&distance='+ $('#distance_search').val();
  url += '&wanted='+ ($('#wanted_search:checked').length);
  return url;
}

/**
 * swap_image is for changing image from thumbnails to big picture.
 * created by Ondrej Letacek Ondrej@nestdesign.com
 **/
//$(document).ready(function() {
$(document).ready(function() {
  $("#big_image_cover img").bind('load readystatechange', function() {
    //if(typeof console !== "undefined")
    //  console.log('load readystatechange'+ $("#big_image_cover img").height());
    big_image_loaded();
  }).each(function(i, val) {
    if(this.complete || this.complete===undefined) {
      //needed for potential cached images
      this.src = this.src;
    }
  });
});
function big_image_loaded(){
  //alert('Before load');
  $("#big_image_cover").css('height', $("#big_image_cover").height());
  $("#big_image_cover img").css('position', 'absolute');
  $("#big_image_cover img").each(function(){
    $(this).css('margin-left', ((480-$(this).width())/2)+'px');
  });
}
//});
function itemImagesLoaded(domObject){
  $(domObject).animate({opacity: 1}, 'slow');
  $("#big_image_cover").animate({height: $(domObject).height()})
  $("#big_image_cover img").each(function(){
    $(this).css('margin-left', ((480-$(this).width())/2)+'px');
  });
}
function swap_image(new_src){
  //if($.is)
  //if($.isReady){
  //try{
    //alert('Jquery not loaded yet'+);
    $("#big_image_cover img").fadeOut('slow', function(){
      $(this).remove();
    });

    new_item   = '<img src="'+new_src+'" style="opacity:0.001;display:block; position:absolute;" />';
    $("#big_image_cover").append(new_item).find('img:last').onImagesLoad({itemCallback: itemImagesLoaded});
    return false;
  //}catch(e){
  //  alert('Error catched -'+e.message);
  //}
  //}
}

function children_height(parent_id){
  var children = $("#"+parent_id).childred();
  var children_height = 0;
  for(i=0;i<children.length;i++) {
    children_height += children[i].height();
  }
  return children_height;
}

function reach_the_end(parent_id){
	var objScroll = document.getElementById(parent_id);
	if ((objScroll.scrollTop+objScroll.clientHeight) >= objScroll.scrollHeight) {
	  return true;
	}
	return false;
}


function set_clear_error(myitem,myerror,formOK){
  if(myitem){
    if(myerror){
      myitem.parentNode.className = 'alert';
      if(formOK)
        myitem.focus();
      formOK = false;
    }else{
      myitem.parentNode.className = '';
    }
  }else
    mydebug(myitem);

  return formOK;
}

function validate_inputtext(itemid,errorid,formOK,displaylive,strlenmin,strlenmax){
  errorblock = document.getElementById(errorid);
	if(document.getElementById(itemid)) {
    var show_error = document.getElementById(itemid).value.length < strlenmin ? true : false;
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
	}
	return formOK;
}

function validate_inputnumber(itemid,errorid,formOK,displaylive,min,max){
  myitem = document.getElementById(itemid);
	if(myitem) {
	  validatenumber(myitem);
    var show_error = myitem.value < min || myitem.value > max ? true : false;
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
	}
	return formOK;
}

function validate_inputfloat(itemid,errorid,formOK,displaylive,min,max,fixed){
  myitem = document.getElementById(itemid);
	if(myitem) {
	  validatefloat(myitem,true,fixed);
    var show_error = myitem.value < min || myitem.value > max ? true : false;
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
	}
	return formOK;
}


function validate_select(itemid,errorid,formOK,displaylive){
  myselect = document.getElementById(itemid);
  /* martin@trarwebu.cz 2010-07-15 (fixed IE6+IE7 failing to search by ID - searching by name too) */
  if(myselect.id != itemid && $.browser.msie && $.browser.version <= '7.0') {
    elms = document.getElementsByTagName('SELECT');
    for(i=0;i<elms.length;i++) {
      if(elms[i].id == itemid) {
        myselect = elms[i];
        break;
      }
    }
  }
  if(myselect){
    myval = myselect[myselect.selectedIndex].value;
    var show_error = myval == 0;
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
  }
  return formOK;
}

function validate_radio(parent_itemid,errorid,formOK,displaylive){
  mydiv = document.getElementById(parent_itemid);
  if(mydiv){
    var show_error = $(mydiv).find('input:checked').length == 0;
		formOK = show_hide_error(parent_itemid, errorid, formOK, displaylive, show_error);
  }
  return formOK;
}

function validate_email(itemid,errorid,formOK,displaylive){
	if(document.getElementById(itemid)) {
	  var show_error = !IsValidEmail(document.getElementById(itemid).value);
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
  }
  return formOK;
}
function validate_checkbox(itemid,errorid,formOK,displaylive){
	if(document.getElementById(itemid)) {
	  var show_error = !document.getElementById(itemid).checked;
		formOK = show_hide_error(itemid, errorid, formOK, displaylive, show_error);
  }
  return formOK;
}
function validate_equal(itemid1, itemid2,errorid,formOK,displaylive){
	if(document.getElementById(itemid1) && document.getElementById(itemid2)) {
	  var show_error = document.getElementById(itemid1).value != document.getElementById(itemid2).value;
		formOK = show_hide_error(itemid1, errorid, formOK, displaylive, show_error);
  }
  return formOK;
}

// provide warning that no images have been uploaded, and confirm
function validate_imagesupload(swfuploader,alreadyuploaded,imgcheckfield) {
	var imgupchk = document.getElementById(imgcheckfield).value
	var stats;
	var flag = false;
	if(typeof(swfuploader) === "object") {
		stats = swfuploader.getStats();
		if(stats != undefined) {
			if(stats.successful_uploads == 0 && alreadyuploaded == 0 && imgupchk == 0) {
				open_popup_quantify('popup_confirm_images');
			} else {
				flag = true;
			}
		}

	}
	// you may as well cancel the return from here, because we need an alternative method to submit the form with the alreadyuploaded field checked
	return flag;
}

function validate_imagesupload_return(flag) {
	if(flag) {
		$.fn.fancybox.close();
		document.getElementById("imguploadchkfield").value = "1";
		$("#to_location").click();
	} else {
		$.fn.fancybox.close();
		document.getElementById("imguploadchkfield").value = "0";
	}
}

function printObject(o) {
	var s = "";
	if(typeof(o) == "object") {
		for(var obj in o) {
			s += obj.toString() + "\n";
		}
	} else s = o.toString() + " is not an object";
	return s;
}

function show_hide_error(itemid, errorid, formOK, displaylive, iserror){
  if(iserror){
    if(formOK)
		  document.getElementById(itemid).focus();
		formOK = false;
    document.getElementById(errorid).style.display = displaylive;
    //document.getElementById(itemid).parentNode.className = 'alert';
    $("#"+itemid).parent().addClass("alert");
  }else{
    errorelement = document.getElementById(errorid);
    if(errorelement)
      errorelement.style.display = 'none';
    //document.getElementById(itemid).parentNode.className = '';
    $("#"+itemid).parent().removeClass("alert");
  }
  return formOK;
}

function IsValidEmail(emailstring) {
	// regex adapted from http://www.yxscripts.com/fg/form.html
	return MatchesPattern(emailstring, '\\w[\\w\\-\\.]*\\@\\w[\\w\\-]+(\\.[\\w\\-]{2,})+');
}
function MatchesPattern(theString, pattern) {
	// Note: regular expressions passed to this function that have escaped
	// characters also need the escape character escaped, otherwise JavaScript
	// will make it disappear, for example:
	// MatchesPattern(mystring, '\w\.\w');    // won't work
	// MatchesPattern(mystring, '\\w\\.\\w'); // will work
	reg = new RegExp(pattern, 'g');
	return Boolean(reg.exec(theString));
}



//************************************
//*  Functions for google maps V3
//************************************

function update_coordinates(marker){
  var testMarker = marker;
  lat = document.getElementById("map_lat");
  lng = document.getElementById("map_lng");
  zoom= document.getElementById("map_zoom");
  var latLng = marker.position ? marker.position : marker.latLng;
  if(lat && lng && zoom){
    lat.value = latLng.lat();
    lng.value = latLng.lng();
    zoom.value= map.getZoom();
    //mymarker_already_moved = 1;
  }
}

function update_marker_by_town(town_select){
  if(town_select.value !== 0){
    url = "/"+js_append_dir+"site/ajax.php";
    $.get(url, {action: 'town_coordinates', type: 'ajax', town_id: town_select.value}, function (tjson) {
      if(typeof tjson.map_lat != "undefined" && typeof tjson.map_lng != "undefined" && typeof tjson.map_zoom != "undefined") {
        latlng = new google.maps.LatLng(tjson.map_lat, tjson.map_lng);
        map.panTo(latlng, tjson.map_zoom);
        mymarker.setPosition(latlng);
        update_coordinates(mymarker);
      }
      if(typeof tjson.error != "undefined")
        alert(tjson.error);
    }, 'json');
  }
}

var customIcons = {
  household: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
    shadow: 'http://freetradeireland.s3.amazonaws.com/site/images/mm_20_shadow.png' //http://office.tvarwebu.cz/freetradeireland/site/images/mm_20_shadow.png
  },
  business: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
    shadow: 'http://freetradeireland.s3.amazonaws.com/site/images/mm_20_shadow.png'
  },
  position: {
    icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
    shadow: 'http://freetradeireland.s3.amazonaws.com/site/images/mm_20_shadow.png'
  }
};


function createMarker(latlng, name, description, mymap, item_type) {
  //var html = "<strong style=\"font-size:130%\">" + name + "</strong> <br/>" + description+"";
  var html = "<div><strong style=\"font-size:130%\">" + name + "</strong> <br/>" + description+"</div>";
  var icon = customIcons[item_type] || {};
  var marker = new google.maps.Marker({
    icon: icon.icon,
    shadow: icon.shadow,
    //iconSize: new google.maps.Size(12, 20),
    //shadowSize: new google.maps.GSize(22, 20),
    //iconAnchor = new google.maps.GPoint(6, 20),
    //infoWindowAnchor = new GPoint(5, 1),
    shape: {coord: new Array(4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0), type:'poly'},
    map: mymap,
    position: latlng
  });
  //if(item_type!='position'){
    google.maps.event.addListener(marker, 'click', function() {
      infoWindow.setContent(html);
      infoWindow.open(mymap, marker);
    });
  //}
  markers.push(marker);
}

function add_markers_array(markerNodes, mymap){
  for (var i = 0; i < markerNodes.length; i++) {
     var name = markerNodes[i].name;
     var map_description = markerNodes[i].map_description;//markerNodes[i].address;
     var distance = parseFloat(markerNodes[i].distance);
     var item_type = markerNodes[i].item_type;
     //var color = markerNodes[i].item_type == 'business' ? 'blue' : 'green';
     var latlng = new google.maps.LatLng(
          parseFloat(markerNodes[i].map_lat),
          parseFloat(markerNodes[i].map_lng));

     createMarker(latlng, name, map_description, mymap, item_type);
    bounds.extend(latlng);
  }
}

var line_circle ;

function drawCircle(map, center, radius)
{
  var circleOptions = {
      center: center,
      radius: radius*1000,
      clickable: false,
      map: map,
      strokeColor: '#004266',
      strokeOpacity: 0.8,
      strokeWeight: 5,
      //fillColor: "#FF0000",
      fillOpacity: 0
    }
  circle = new google.maps.Circle(circleOptions);
  //circle.setMap();
}

function add_ireland_boundaries(bounds){
  north_east = new google.maps.LatLng(ireland_lat_north, ireland_lng_east)
  south_west = new google.maps.LatLng(ireland_lat_south, ireland_lng_west)
  bounds.extend(north_east);
  bounds.extend(south_west);
  return bounds;
}


function set_cookie(name,value,time) {
    if (time) {
        var date = new Date();
        date.setTime(date.getTime()+time);
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function get_cookie(name) {
    var name_eq = 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(name_eq) == 0) return c.substring(name_eq.length,c.length);
    }
    return null;
}

function set_font_size(size, days){
  //console.log($("body").parseClassToArray('page-font'));
  set_cookie('page_font_size',size,days*24*60*60*1000)
  $('body').removeClass('page-font-small').removeClass('page-font-medium').removeClass('page-font-large').addClass('page-font-'+size);//css('font-size', get_cookie("page_font_size"));
}
/*
if(get_cookie("page_font_size") != null){
    document.write('<style>');
    document.write('body{');
    document.write('font-size:'+ get_cookie("page_font_size"));
    document.write('}');
    document.write('</style>')
}
*/
/**
  * flag_item(): Shows flag form and submits it
  *
  * @param mixed link: The originator object (must have attribute action or href) or the request url (must have #flag-item-reason allready created)
  * @note looks for #flag-item-reason in siblings of originator
  * @note looks for h1 tag in siblings to place #flag-item-reason after that (if not prosent)
  * @requires getChildrenHeight() jquery function (underneat)
**/

function flag_item(link) {
  url = '';
  data = {};
  is_form = false;
  // get url we need to load
  if(typeof link == 'object' && link.tagName == 'INPUT') {
    link = link.form.action;
  }
  if(typeof link == 'object' && (typeof link.href != 'undefined' || typeof link.action != 'undefined')) {
    if(link.tagName.toUpperCase() == 'FORM') {
      is_form = true;
      url = link.action;
      // gather the users data
      data['sbmt'] = 'Submited';
      $(':text, textarea, select, :checked, :hidden', link).each(function () {
        data[$(this).attr('name')] = $(this).attr('value');
      });
    } else {
      url = link.href;
    }
  } else if (typeof link == 'string') {
    url = link
  }

  // create / fix container
  if($('#report_item_box').length == 0 && $(link).siblings('#report_item_box').length == 0) {
    $(link).parents('#item_links').siblings('h1').after('<div id="report_item_box"></div>');
  } else if(!is_form) {
    c = $('#report_item_box');
    if(c.is('.allready-used')) {
      if(c.css('display') == 'none') {
        c.stop(true).slideDown('slow', function () {
          $(this).css('height', '');
        });
      } else {
        c.slideUp('slow', function() {
          if(!$(this).is(':animated'))
            $(this).remove();
        });
      }
      return false;
    }
  }

  /* submit the data */
  $.post(url, data, function (tjson) {
    c = $('#report_item_box');
    if(typeof tjson.html != 'undefined') {
      // we have got whole HTML, put it in
      if(!c.hasClass('allready-used')) {
        // do not expand the container immediately
        c.addClass('allready-used').css({overflow: 'hidden', height: 0})
      } else {
        // we want animation to small one
        c.css('height', c.css('height'));
      }
      h = c.html(tjson.html).getChildrenHeight();
      c.animate({height: h}, 'slow', function () {
        $(this).css('height', '');
      });
    } else {
      objs = $('#report_item_box').find('.error'); // clean the errors (we have a new ones)
      // go through all errors and place them into the content
      if(typeof tjson.errors != 'undefined') {
        for(i in tjson.errors) {
          obj = mark_error('#flag_'+i, tjson.errors[i], c.find('.global-errors'));
          objs.each(function (n) {
            if($(obj).get(0) == $(this).get(0))
              //objs[n] = null;
              delete objs[n];
          });
        }
      }
      if(objs.length > 0) {
        try {
          objs.slideUp('slow', function () {
            $(this).remove();
          });
        } catch (e) {
        }
      }
    }
  }, 'json');
}

/**
* mark_error(): place a error message after the input
*
* @param String input: the selector of input element (must be ID)
* @param String msg: The message to display
* @param jQuery default_cont: The default container for messages (when input is not found)
*/
function mark_error(input, msg, default_cont) {
  input_str = input;
  input = $(input);
  if(input.length > 0) {
    if((cont = $(input_str+'_error')).length == 0) {
      // place an error container after the input
      $(input).after((cont = $('<div id="'+input_str.substring(1)+'_error'+'" class="error flag-error">')));
    }
    h = cont.css({height: cont.height(), overflow: 'hidden'}).html('<div>'+msg+'</div>').getChildrenHeight();
    cont.animate({height: h});
    return cont;
  } else if(default_cont.length > 0) {
    h = default_cont.css({height: default_cont.height(), overflow: 'hidden'}).append((cont = $('<div id="'+input_str.substring(1)+'_error'+'" class="error">').html(msg))).getChildrenHeight();
    default_cont.animate({height: h});
    return cont;
  }
}

$.extend($.fn, {
  /* calculate all children's height */
  getChildrenHeight: function () {
    children = $(this).children();
    total = 0;
    for(i=0;i<children.length;i++) {
      total += $(children[i]).height()+parseInt($(children[i]).css('marginTop'))+parseInt($(children[i]).css('marginBottom'))+parseInt($(children[i]).css('paddingTop'))+parseInt($(children[i]).css('paddingBottom'));
    }
    return total;
  }
});

