if(!window.console) {console = {}; console.log = function(){}; console.error = function(){};}

/**
 * SuperToggle - toggle element with a link - more info at http://wiki.github.com/blmstr/jquery-plugins/
 * @author Joel Larsson
 * 
 */
jQuery.superToggle = function() {
  var active_class = "active";
	var inactive_class = "inactive";
	$("a.sp").bind("click", function() {
		
		// look for the href to be used for the toggler element id
		var hash = this.href.split('#');
		var prefix = hash[hash.length-1];
		
		var toggleEl = $("#"+prefix);
		if (toggleEl.css("display") != "none") {
			toggleEl.addClass(inactive_class).removeClass(active_class).hide();
			$(this).addClass(inactive_class).removeClass(active_class);
		} else { 
			toggleEl.addClass(active_class).removeClass(inactive_class).show();
			$(this).addClass(active_class).removeClass(inactive_class);
		}
		return false;
	});
};

// imagify the text! (make dynamic server images of the text to get the correct font)
jQuery.fn.imagify = function() {
  return this.each(function() {
    var el = this;
    var text = el.innerHTML.trim();
    
    if (text == "") return;

    if (typeof text != "string") {
      el = text;
    }
    
    text = text.toUpperCase();
    var style = "big";
    if ($(el).hasClass("med-h")) {
      style = "medium";
    } else if ($(el).parent().hasClass("menu-item") || $(el).hasClass("small-h")) {
      style = "small";
    } else if ($(el).hasClass("xsmall-h")) {
      style = "xsmall";
    } else if ($(el).hasClass("msmall-h")) {
      style = "msmall";
    } else if (el.tagName.toLowerCase() == "label") {
      style = "small"
    } 
    
    var bg_color = null;
    if ($(el).hasClass("green-bg")) {
      bg_color = "&bg-color=8fe27a";
    }
    
    var color = null;
    if ($(el).css("color")) {
      color = "&color="+colorToHex($(el).css("color"));
      color = color.replace("#", "");
    }
    // Replace the text with an image
    this.innerHTML = "";
    var img_src = "/wp-content/themes/liggprofilen/font.php?text="+text+"&style="+style+""+color+bg_color;
    var img = $('<img src="'+img_src+'" alt="'+text+'"/>');
    img.appendTo(el);
    
    
  });
}
// Create trim function for string object
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

jQuery.fn.tooltip = function() {
  return this.each(function() {
    var el = this;
    var t_el;
    var text;
    
    $(el).bind("mouseover", function(e) {
      e.preventDefault();
      
      text = el.title;
      el.title = "";

      // tooltip element
      t_el = $('<div class="tooltip"><span class="inner">'+text+'</span></div>');

      t_el.appendTo(el);
      return false;
    }).bind("mouseout", function() {
      t_el.remove();
      el.title = text;
    });
    
    
    
  });
}

$(document).ready(function() {
  
  if ($.fn.tweets) {
    // init tweet listing
    $('#tweets ul').html("").tweets({ 
      tweets: parseInt($('#tweets').attr("data-number")) || 3, 
      username: "kondom08" 
      //search_text: "%23kondom"
    }, function() {
      var el = $(".vc");
      var sibling = el.siblings();
      $("a", el).css({"width": el.width()+"px", "height": el.siblings().height()+"px", "display": "table-cell", "vertical-align": "middle"});
      sIFR.replaceElement("#tweets p.text", named({sFlashSrc: "/wp-content/themes/liggprofilen/swf/sifr-knockout.swf", sColor: "#000", sCase: "upper"}));
      sIFR.replaceElement("#tweets span.date", named({sFlashSrc: "/wp-content/themes/liggprofilen/swf/sifr-knockout.swf", sColor: "#49DBEA", sCase: "upper"}));
    });
  }
  
  var container = $("#safer-sex-container");
  if (container.is("*"))
    get_feed(container);
  
  $.superToggle();
  
  $(".export-graph").bind("click", function() {
    if (main_graph)
      main_graph.exportChart();
    return false;
  });
  
  // $(".big-h").imagify();
  imagify();
  
  $(".user-props-list li").tooltip();
  
  $(".share-big-btn.sp, .share-btn.sp").bind("click", function() {
    add_overlay();
    return false;
  });
  $(".close-btn").bind("click", function() {
    remove_overlay();
    $("#share-layer").addClass("inactive").removeClass("active");
    return false;
  });
  
  if ($("body").hasClass("graph-only-view")) {
    setTimeout(function() {
      add_invisible_overlay();
    }, 1000);
    
  }
  
  // init placeholder plugin
  if ($.fn.placeholder)
    $('input[placeholder], textarea[placeholder]').placeholder();
  
  
  set_equal_heights();
  
  if(typeof sIFR == "function"){
    // sIFR.replaceElement(".text", named({sFlashSrc: "/wp-content/themes/liggprofilen/swf/sifr-knockout.swf", sColor: "#000", sCase: "upper"}));
  };
  
  // Style SELECT-menus
  if( $('body.page-template-page-sok-jamfor-php #content select:first').is('select') ) {
	  $('body.page-template-page-sok-jamfor-php #content select').selectmenu({ maxHeight: 450, menuWidth: 140, style: 'popup' });
	 }
	/*
	$("body.page-template-page-sok-jamfor-php #content a.ui-selectmenu").bind("click", function(e) {
    e.preventDefault();
	});
	*/  
	
	//sIFR.replaceElement("div.lay-time", named({sFlashSrc: "/wp-content/themes/liggprofilen/swf/sifr-knockout.swf", sColor: "#8fe27a", sCase: "upper", sFlashVars: "textalign=right"}));	
});

// set equal heights on columns
function set_equal_heights() {
  var selector = "div.cols > .br";
  
  var el = $(selector);
  var siblings = el.siblings();
  if( !$('body').hasClass('page-template-page-fraga-olle-php') ) {
  
  var lc = $('#content > div.cols > .col5:first');
  var rc = $('#content > div.cols > .col3.right:first');  
  
  if( $(rc).height() > $(lc).height() ) {
  	$(lc).height( $(rc).outerHeight() );
  }
  
  /*
	  siblings.each(function() {
	    
	    var sibling_height = $(this).height();
	    var el_ = $(this).siblings();
	    var el_height = el_.height();
	    
	    if (sibling_height > el_height) {
	      
	      if (el_.has("#tweets").is("*") == true)
	        return;
	        
	      el_.css({"height": sibling_height+"px"});
	    }
	    
	    //var el_height = $(this).siblings().height();
	  })
	  */
  }
  
}

function add_invisible_overlay() {
  $("#main-graph").append($('<div class="invisible-overlay"></div>'));
  $("#main-graph-2").append($('<div class="invisible-overlay"></div>'));
  
}
function add_overlay() {
  return $('<div class="overlay"></div>').appendTo(document.body);
}
function remove_overlay() {
  return $(".overlay").remove();
}

function imagify() {
  // $(".big-h, .med-h, #main_nav ul li a").imagify();
  $(".big-h, .med-h, .small-h, .vem-ligger-hur-form .container label, .xsmall-h, .msmall-h").imagify();
}

function get_feed(container) {
  $.ajax({
      url: "/wp-content/themes/liggprofilen/proxy.php?url=http://www.sakraresex.se/RSS/Fragor-och-svar/",
      type: 'GET',
      dataType: 'xml',
      success: function(xml) {
        var number_of_items = 10;
        var i = 0;
        var ul = $('<ul></ul>').appendTo(container);
        $(xml).find("item").each(function() {
          if (i < number_of_items) {
            // var time = $(this).find("pubDate").text();
            //            var date = new Date(Date.parse(time));
            //            time = monthNames[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
            var desc = $(this).find("description").text();
            var link = $(this).find('link').text();
            var title = $(this).find('title').text();

            var item = $('<li><a href="'+link+'"><h3 class="title">'+title+'</h3><p class="desc">'+desc+'</p></a></li>');
            item.appendTo(ul);
          }
          i++;
        });

      }
  });
}

function basic_options(db_points, gyro_points, el_id, height, bg_color, width) {
  height = typeof height == "undefined" ? null : height;
  width = typeof width == "undefined" ? null : width;
  bg_color = typeof bg_color == "undefined" ? null : bg_color;
  
  var plot_options = {
    spline: {
      shadow: false,
      lineWidth: 4,
      states: {
        hover: {

           enabled: false
        }
      },
      marker: {
        enabled: false,
        states: {
           hover: {
              enabled: false
           }
        }   
      }
    }
  };

  colors = ['#f792ac', '#49dbea', '#f792ac', '#49dbea', '#f792ac', '#49dbea', '#f792ac', '#49dbea', '#f792ac', '#49dbea'];
  //var colors = ['#000000', '#666666'];  
  
  var options = {
    chart: {
      spacingLeft: 0,
      spacingRight: 0,
      spacingTop: 0,
      spacingBottom: 15,
      backgroundColor: bg_color,
      renderTo: el_id || "chart-container",
      defaultSeriesType: 'spline',
      width: width,
      height: height,
      style: 'border: 1px solid #f00;'
    },
    title: {
      text: null
    },
    legend: {
      align: "left",
      verticalAlign: "top",
      borderWidth: 0,
      layout: "vertical",

      enabled: false
    },
    point: {
      marker: {enabled: false}
    },
    xAxis: {
      // title: {
      //   text: "Tid"
      // },
      //categories: ["Start", " ", " ", " ", " ", " ", " ", "Klart"],
      // categories: null,
      // categories: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
      lineColor: "#8fe27a",
      lineWidth: 5,
      // gridLineWidth: 0,
      // gridLineDashStyle: null,
      tickWidth: 0,
      labels: {
        enabled: false,
        style: {
          color: "#000000",
          fontSize: "18px",
          fontFamily: "Conv_ChaletComprime-CologneEight",
          paddingTop: "5px"
        },
        y: 25

      }
    },
    yAxis: {
      title: {
         text: null
      },
      minPadding: 0.2,
      maxPadding: 0.2,
      min: 0,
      max: 101,
      gridLineWidth: 0,
      labels: {
        enabled: false
      }

    },
    tooltip: {
      enabled: false
    },
    series: [{
      name: 'Rytm',
      data: gyro_points
    }, {
      name: 'Ljud',
      data: db_points
    }],
    plotOptions: plot_options,
    colors: colors,
    exporting: {
      enabled: true,
      filename: "liggprofil",
      buttons: {
        exportButton: {},
        printButton: {
          enabled: false
        }
      }
    },
    navigation: {
      buttonOptions: {
        enabled: false
      }
    },
    credits: {
      enabled: false
    }
  };
  return options;
}

function create_graph(db, gyro, id, label, classname, time, height, bg_color, width) {
  classname = typeof classname == "undefined" || !classname ? "big-h" : classname;
  var chart = new Highcharts.Chart(basic_options(db, gyro, id, height, bg_color, width));
  label = label || "Senaste ligg";
  //$('#'+id+' .highcharts-container tspan').last().remove();
  var el = $("#"+id);
  
  //if (!el.hasClass("tiny-graphs"))
    
  if (!el.hasClass("tiny-graphs") && !el.hasClass("medium-graphs")) {
  	$(el).parent().append('<div class="chart-label"></div>');
    //$('<div class="chart-label"></div>').appendTo($(">div", el));
    el.css({"position": "relative", "margin-bottom": "15px", "overflow": "visible"});
  }
  
  $('<h2 class="'+classname+'">'+label+'</h2>').css({"position": "absolute", "z-index": "99999", "top": 0, "left": 0, "margin-top": "-3px", "line-height": "100%"}).appendTo($(el).parent());
  
  // if (!el.hasClass("tiny-graphs") && !el.hasClass("medium-graphs"))
  //     $('<div class="chart-time-label"></div>').appendTo(el);
    
  if (typeof time !== "undefined" && time && !el.hasClass("tiny-graphs") && !el.hasClass("medium-graphs"))
    $(el).parent().append('<div class="lay-time">'+time+'</div>');
  
  $(el).bind("click", function() {
    //window.location = "/ligg?id="+
    //return false;
  });
  
  //$("")
  return chart;

}

function colorToHex(color) {
    if (color.substr(0, 1) === '#') {
        return color;
    }
    var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
    
    var red = parseInt(digits[2]);
    var green = parseInt(digits[3]);
    var blue = parseInt(digits[4]);
    
    var rgb = blue | (green << 8) | (red << 16);
    return digits[1] + '#' + rgb.toString(16);
};

function format_avg_time(sec) {
  sec = parseInt(sec);
  
  
  if (!sec) {
    result = "okänd tid";
  } else if (sec >= 60) {
    //result = Math.round(sec / 60) + " min";
    min = Math.floor(sec / 60);
    sec = Math.floor(sec % 60);
    result = min + ' min och ' + sec + ' sek';    
    
  } else {
    result = sec+" sek";
  }
  return result; 
  
};

function format_exact_time(sec) {
  if (!sec) {return "okänd tid";}
  
  
  
  var min = Math.floor(sec / 60);
  
  sec = sec % 60;
  if (sec < 10) {
    sec = "0"+sec;
  }
  
  var hour = 0;
  if(min >= 60){
  	hour = Math.floor(min / 60);
  	min = min % 60;
	}
  
  if (min < 10) {
    min = "0"+min;
  }
  
  if (hour < 10) {
    hour = "0"+hour;
  }
  
  var result = hour + ":"+min+":"+sec;
  
  return result;
}
