$j(document).ready(function(){

/* feature article - solve: h1 and text witgout any tag */
  function headerWrap(location, header){
    $j(location + " " + header).wrap("<div></div>");
    $j(location + " div " + header).parent("div").addClass("m_top20");
    $j(location + " div " + header).parent("div.m_top20").prepend('<div class="float_l"></div><div class="clear_l"></div>');
    $j(location + " div " + header).css("margin-top","0px");
  }

/* anchors class*/
  $j('#article a[@href=""]').addClass("anchor");
  $j('#article a.addthis_button_email').removeClass("anchor");
  $j('#article h1 a.anchor').removeClass("anchor");

function quotations($that){
  if($j($that).html()!=null)
    strText= $j($that).html()
  else
    strText="None";

  strTarget="&amp;quot;";
  strSubString="&quot;";
  var intIndexOfMatch = strText.indexOf(strTarget);

// Keep looping while an instance of the target string still exists in the string.
  while (intIndexOfMatch != -1){
  strText = strText.replace(strTarget, strSubString)

// Get the index of any next matching substring.
  intIndexOfMatch = strText.indexOf(strTarget);
}

  strTarget="&amp;nbsp;";
  strSubString="&nbsp;";
  var intIndexOfMatch = strText.indexOf( strTarget );

// Keep looping while an instance of the target string still exists in the string.
  while (intIndexOfMatch != -1){
    strText = strText.replace(strTarget, strSubString)

// Get the index of any next matching substring.
    intIndexOfMatch = strText.indexOf(strTarget);
  }
  strTarget="&amp;amp;";
  strSubString="&amp;";
  var intIndexOfMatch = strText.indexOf(strTarget);

// Keep looping while an instance of the target string still exists in the string.
  while (intIndexOfMatch != -1){
    strText = strText.replace(strTarget, strSubString)

// Get the index of any next matching substring.
    intIndexOfMatch = strText.indexOf( strTarget );
  }
  $j($that).html(strText);	
}

  $j("li").each(function(){
    quotations(this);
  });
  $j("p").each(function(){
    quotations(this);
  });

/* Show CLOSE button on Terms and Conditions page */
  if ($j(document).getUrlParam("register") == 1) {
    $j('form.tc_close').show();
  }

/* adds clear div after each even element */
   $j('div.pos_even').each(function(){
     $j(this).after('<div class="clear"></div>');
   });

/* text size for Article template */
  $j('div#art_ob_date').after('<div id="art_ob_text_size">Text size</div><div id="text_sizes"><a href="#" id="text_size_s">A</a>&nbsp;<a href="#" id="text_size_m">A</a>&nbsp;<a href="#" id="text_size_b">A</a></div>');

  $j('div#text_sizes a').click(function(){
    var new_size = $j(this).attr('id');
    NewArticleSize(new_size);
  });

  $j('#article #art_comment_bar').css('border','none');

/* highlighting article header text */
  if($j('.text_highliting').html()!=null){
    var $htext = $j('.text_highliting').html();
    $htext = $htext.replace("&amp;", "&");
  }
  var $hcolor = $j('input#highlight_color').val();
  //var $htext = $j('input#text_to_highlight').val();
  if ($htext != null && $htext != ''){
    $htext = $htext.toUpperCase();

    $j('div#art_header_left h3').each(function(){
      var $h_new_text = $j(this).text();
      $h_new_text = $h_new_text.toUpperCase();
      $h_new_text = $h_new_text.split($htext);
      if ($h_new_text.length > 1) {
        $htext = $h_new_text[0] + "<span id='h_text'>"+$htext+"</span>"+$h_new_text[1];
      }
      else { 
        $htext = $h_new_text[0];
      }
      $j(this).html($htext);
    });

/* added temp */
$j('div#art_header_left h1').each(function(){
      var $h_new_text = $j(this).text();
      $h_new_text = $h_new_text.toUpperCase();
      $h_new_text = $h_new_text.split($htext);
      if ($h_new_text.length > 1) {
        $htext = $h_new_text[0] + "<span id='h_text'>"+$htext+"</span>"+$h_new_text[1];
      }
      else { 
        $htext = $h_new_text[0];
      }
      $j(this).html($htext);
    });
/* added temp end */

    $j('span#h_text').css({'color' : $hcolor});
  }

/* hide previous/next pagination if there is only one page results */
  $j('#list_pages_nav').each(function(){
    if(!this.getElementsByTagName("a")[0]) {
      $j(this).hide();
    }
  })
  $j('#article .prevnext').each(function(){
    if(!this.getElementsByTagName("a")[0]) {
      $j(this).hide();
    }
  })

/* goes to the bottom of the screen after submitting a comment */
  var new_action = $j('#page_asset_builder_999').attr('action') + "#page_asset_builder_999";
  $j('#page_asset_builder_999').attr('action', new_action);

/* MY BABY CALENDAR functionality */

  var current_date = $j.PHPDate("U", new Date());
  var temp_date = $j(document).getUrlParam("month") + "/" + $j(document).getUrlParam("day") + "/" + $j(document).getUrlParam("year");
  var user_date = $j.PHPDate("U", new Date(temp_date));

  var date_difference = parseInt((current_date - user_date) / 2592000) + 1;

  var months = [1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715, 1716];
  var current_month = $j.PHPDate("n", new Date());

  var show_items = 3;
  var existing_items = 12 - date_difference + 1;

  if (date_difference < 13 && user_date < current_date) {
    var add_section = 0;
    var bc_counter = 0;
    while(date_difference < 13) {
      if (bc_counter %3 == 0) { add_section = add_section + 1; }
      if(current_month>12) {
        current_month=1;
      }
      $j('li.item' + date_difference).addClass('section' + add_section);
      $j("li.item" + date_difference + " div.babycalendar_left_box").html("<img src='./?a=" + months[current_month-1]+"' /><div></div>" + $j("li.item" + date_difference + " div.babycalendar_left_box").html());
      date_difference = date_difference + 1;
      current_month = parseInt(current_month)+1;
      bc_counter = bc_counter + 1;
    };
    date_difference = date_difference - 1;
  };

  if ($j('.section2').length>0) {
    content = $j('.section1:last').html();
    $j('.section1:last').html(content + '<div class="prevnext"><a href="#" class="anext1">Next</a></div>');
  };
  if ($j('.section2').length>0 && $j('.section3').length==0) {
    content = $j('.section2:last').html();
    $j('.section2:last').html(content + '<div class="prevnext"><a href="#" class="aprev2">Previous</a></div>');
  };
  if ($j('.section2').length>0 && $j('.section3').length>0) {
    content = $j('.section2:last').html();
    $j('.section2:last').html(content + '<div class="prevnext"><a href="#" class="aprev2">Previous</a> | <a href="#" class="anext2">Next</a></div>');
  };
  if ($j('.section3').length>0 && $j('.section4').length==0) {
    content = $j('.section3:last').html();
    $j('.section3:last').html(content + '<div class="prevnext"><a href="#" class="aprev3">Previous</a></div>');
  };
  if ($j('.section3').length>0 && $j('.section4').length>0) {
    content = $j('.section3:last').html();
    $j('.section3:last').html(content + '<div class="prevnext"><a href="#" class="aprev3">Previous</a> | <a href="#" class="anext3">Next</a></div>');
    content = $j('.section4:last').html();
    $j('.section4:last').html(content + '<div class="prevnext"><a href="#" class="aprev4">Previous</a></div>');
  };

  $j('.anext1').click(function(event){
    $j('.section1').hide();
    $j('.section2').show();
  });
  $j('.aprev2').click(function(event){
    $j('.section2').hide();
    $j('.section1').show();
  });
  $j('.anext2').click(function(event){
    $j('.section2').hide();
    $j('.section3').show();
  });
  $j('.aprev3').click(function(event){
    $j('.section3').hide();
    $j('.section2').show();
  });
  $j('.anext3').click(function(event){
    $j('.section3').hide();
    $j('.section4').show();
  });
  $j('.aprev4').click(function(event){
    $j('.section4').hide();
    $j('.section3').show();
  });

  if(date_difference >= 13 || user_date > current_date) {
    $j('div.babycalendar_noresults').show();
  }
/* MY BABY CALENDAR end */

/* SEARCH UNIT - date ranges */
  var dateTo = new Date();
  var dateFrom = new Date();
  var milliTo = dateTo.getTime();
  var milliFrom = 0;

  $j("#select_div select").change(function() {
    milliFrom = milliTo - $j("#select_div select").val();
    dateFrom.setTime(milliFrom);

    $j("div.input_hidden input[@id^='queries_date_query_fromvalue']:eq(0)").val(dateFrom.getFullYear());
    $j("div.input_hidden input[@id^='queries_date_query_fromvalue']:eq(1)").val(dateFrom.getMonth() + 1);
    $j("div.input_hidden input[@id^='queries_date_query_fromvalue']:eq(2)").val(dateFrom.getDate());
    $j("div.input_hidden input[@id^='queries_date_query_tovalue']:eq(0)").val(dateTo.getFullYear());
    $j("div.input_hidden input[@id^='queries_date_query_tovalue']:eq(1)").val(dateTo.getMonth() + 1);
    $j("div.input_hidden input[@id^='queries_date_query_tovalue']:eq(2)").val(dateTo.getDate());
  });
/* SEARCH UNIT end */

/* CHALLENGE ARTICLE - show/hide advices */
  $j('#advice_content li:first').show();
  $j('#advice_content li:first+li').show();

  var n = $j('#advice_content li').size();
  if (n <= 2){
    $j('#challenge_advice button').hide();
  }

  $j('#challenge_advice button').click(function() {
    $j('#advice_content li').toggle()
  }).toggle(function(){
    $j('#advice_content li:first').show();
    $j('#advice_content li:first+li').show();
    $j('#challenge_advice button').removeClass();
    $j('#challenge_advice button').addClass('minimise');
  },function() {
    $j('#advice_content li:first').show();
    $j('#advice_content li:first+li').show();
    $j('#challenge_advice button').removeClass('minimise');
  });
/* CHALLENGE ARTICLE end */

/* HEAR AN EXPERT div - all articles button functionality */
  $j('#all_articles').toggle(
    function(){ 
      $j('div.expert_articles').show();
      $j('#all_articles img').hide();
      $j('#all_articles').addClass('minimise');
    },
    function(){
      $j('div.expert_articles').hide();
      $j('#all_articles').removeClass();
      $j('#all_articles img').show();
    }
  );

/* adds target blank to each link with external_link class */
  $j('a.external_link').attr('target','blank');

/* removes article word from article/asset type */
  $j('span.article_type').each(function(){
    var new_text = $j(this).text();
    new_text = new_text.substring(0,new_text.length-8);
    $j(this).text(new_text);
  });

/* article news quote */
  var quote_cont = $j("body.news #article #art_quote").html();
  $j("body.news #article #art_quote").html("");
  $j("body.news #article div.wq").after(quote_cont + '<div class="clear"></div>');
  $j("body.news #article #quote").addClass("block");

/* FEATURE ARTICLE TWEAKST */
  if ($j('input#is_feature').val() == 'true') {

/* adds a dropCap to Feature article */
    $j('div#feature_article div p:first').DropCap();

/* improves content formating - removes img from h1 - content incorrectly formated */
    if ($j('div#feature_article h1 img')){
      $j('div#feature_article h1 img').each(function(){
        var $h1img = $j(this);
        $j(this).parent('h1').next('ul').after('<div class="clear"></div>');
        $j(this).parent('h1').after($h1img);
      });
    }
    if ($j('div#feature_article h1 a img')){
      $j('div#feature_article h1 a img').each(function(){
        var $h1img = $j(this);
        $j(this).parent('a').parent('h1').next('ul').after('<div class="clear"></div>');
        $j(this).parent('a').parent('h1').after($h1img);
      });
    }
  }
/* FEATURE ARTICLE TWEAKST end */

/* SAVE THIS ARTICLE FUNCTIONALITY */
  var $already_added = $j('input#already_added').val();
  if ($already_added == 'true'){
    alert('Article was added to "My Links" section.');
  }
  var $is_member = $j('input#is_member').val();
  if ($is_member == 'true'){
    var $mylinks_url = $j('input#mylinks_url').val();
    var $mylinks_id = $j('input#mylinks_id').val();
    $j('div#art_save a').attr('href', $mylinks_url+'?my_link=true&mylink_asset_id='+$mylinks_id)
  }
  if ($is_member == 'false'){
    $j('div#art_save a').addClass('nota_member').removeAttr('href');
  }

  $j('a.nota_member').click(function(){
    alert("In order to use this functionality you need to be logged in.");
  });
/* SAVE THIS ARTICLE FUNCTIONALITY end */

/* underlined links */
  $j("#article u a").parent("u").css("text-decoration","none");

/* feature article - solve: h1 and text without any tag */
  $j("#feature_article h1").wrap("<div></div>");
  $j("#feature_article div h1").parent("div").addClass("m_top20 headwrapper");

  //$j("#feature_article div h1").parent("div.m_top20").prepend('<div class="float_l"></div><div class="clear_l"></div>');
  $j("#feature_article div h1").css("margin-top","0px");

  //$j("#feature_article div.headwrapper").before('<div class="clear"></div>');
  $j("#feature_article div.headwrapper").next().css("margin-top","0px");

  $j("#feature_article li img").each(function() {
    var imgw = $j(this).width();
    if (imgw > 630) $j(this).width("620px");
  });

  $j("#challenge_article h1").next().css("margin-top","0px");

/* RATING FUNCTIONALITY JABBA */
  var full_star_url = $j('#full_star_url').val();
  var empty_star_url = $j('#empty_star_url').val();
  var half_star_url = $j('#half_star_url').val();
  var article_url = $j('#asset_url').val();
  var loader_url = $j('#ajax_loader_url').val();

  var sum = $j('#rating_sum').val();
  var count = $j('#rating_count').val();
  var average = $j('#rating_average').val();

  if (sum == "") sum = parseInt(0);
  if (count == "") count = parseInt(0);
  if (average == "") average = "0";
  else average = (Math.round(average*100))/100;

/* draws rating for currently viewed article */
  drawCurrent('#art_rate', average);

/* draw in asset listings */
  $j('.item_list_rating').each(function(intIndex){
    var rate = $j(this).find('.average_rating').val();
    drawCurrent('.item_list_rating:eq('+intIndex+')', rate);
  });

/* draw in right column */
  $j('.related_news_stars').each(function(intIndex){
    var rate = $j(this).find('.average_rating').val();
    drawCurrent('.related_news_stars:eq('+intIndex+')', rate);
  });

/* put zero in reviews */
  $j('a.reviews_link').each(function(){ if ($j(this).html()==" Reviews") $j(this).html("0 Reviews");});
  $j('.item_list_rating p').each(function(){ if ($j(this).html()==" Reviews") $j(this).html("0 Reviews");});

/* apply hover and click actions to stars */
  $j('#art_rate img').each(function(intIndex){
    $j(this).hover(function(){
      highlight('#art_rate', intIndex + 1);
    },
    function(){
      drawCurrent('#art_rate', average);
    });
    $j(this).click(function(){
      count = parseInt(count) + 1;
      sum = parseInt(sum) + intIndex + 1;
      average = sum/count;		
      average = (Math.round(average*100))/100;
      $j('#art_rate').html('<img src=\"' + loader_url +'\" />');
      $j.ajax({
          type: "GET",
          url:  article_url,
          data: "average=" + average + "&sum=" + sum + "&count=" + count,
          success: function(){
            $j('#art_rate').html('<p>Rating saved.</p>');
            alert('Thank you for your rating! This will be reflected in the average rating shown.');
          }
      });
    });
  });

/* hovering highligthing */
  function highlight(element, num_stars) {
    var current = full_star_url;
    $j(element + ' img').each(function(intIndex) {
      if (intIndex == num_stars) {
        current = empty_star_url;
      }
      if ($j(this).attr('src') != current) {
        $j(this).attr('src', current);
      }
    });
  };

/* drawing current rating in specified container with stars */
  function drawCurrent(element, average) {
    var string = "" + average;
    var tab = string.split(".");
    var main = tab[0];
    var rest = tab[1];
    if (rest == undefined) {
      highlight(element, main);
      return;		
    }
    rest = "" + rest;
    if (rest.length == 1) {
      rest = parseInt(rest) * 10;
    }
    rest = parseInt(rest);
    if (rest < 25) {
      highlight(element, main);
      return;
    }
    if (rest > 25 && rest < 75) {
      highlight(element, main);
      $j(element + ' img:eq('+main+')').attr('src', half_star_url);
      return;
    }
    if (rest >= 75) {
      highlight(element, main + 1);
      return;
    }
  };
/* RATING FUNCTIONALITY end */

/* YOU MIGHT ALSO ENJOY hiding when there is only one feature on Giveaways */
  if ($j('#gaw_content').length == 1) {
    if ($j('#related_news .related_news_item').length == 0) {
      $j('#related_news').hide();
      $j('#did_you_know').css('margin-top','12px');
    }
  }
/* YOU MIGHT ALSO ENJOY hiding end */

/* EMAIL VALIDATION */
  $j("label").each(function(){
    if($j(this).attr('for') == 'metadata_field_text_1009_value'){
      $j(this).next('input').keyup(function(){
        var email = $j(this).val();

        if (isValidEmailAddress(email)) {
          $j(this).attr("style", "border: #3D9B35 solid 2px; background-color: #A9DC93;");
          $j('button#sq_commit_button').removeAttr("disabled");
        }
        else {
          $j(this).attr("style", "border: #c9282d solid 2px; background-color: #fdb1c0;");
          $j('button#sq_commit_button').attr("disabled", "disabled");
        }
      });
    }
  });
/* EMAIL VALIDATION end */

/* MAKE IT - SLIDES start */
  $makeit_slides = $j('#makeit_slides').val();

/* MAKE IT ARTICLE - ADDS A TEXT */
  if ($j('input#slides_amount').val() > 1){
    $j('div.notime_toview').html('<h3>No time to watch this slideshow? Simply add this page to your bookmarks and come back later.</h3><p></p>'); }
  else if ($j('div#youtube_movies').length == null){
    $j('div.notime_toview').html('<h3>No time to watch this video? Simply add this page to your bookmarks and come back later.</h3><p></p>'); }
  else {
    $j('div.notime_toview').html('<h3>No time to make this now? Simply add this page to your bookmarks and come back later.</h3><p></p>'); }

  if ($makeit_slides == 'true'){

/* create images array */
    var img_list = new Array();
    $j('ul#slideimages li').each(function(i){
      img_list[i] = $j(this).attr('id');
    });

/* show navigation */
    if (img_list > '1'){$j('div.prevnext_navigation').css('display','block');}

/* create circled navigation */
    $j('div.nav_index').append('<ul></ul>');
    for (var i=0;i < img_list.length; i++){
      $j('div.nav_index ul').append('<li><span>'+i+'</span></li>');
    };
    $j('div.nav_index ul').each(function(){
	  $j(this).children('li:first').addClass('current');
    });

/* prev next buttons functionality */
    var $counter = 0;
    $j('a.next_slide').click(function(){
      $j('#'+img_list[$counter]).removeClass('current');
      $j('div.nav_index ul').each(function(){$j(this).children('li').eq($counter).removeClass('current');});
      $counter+=1;
      if ($counter == img_list.length) {$counter=0;}
      $j('#'+img_list[$counter]).addClass('current');
      $j('div.nav_index ul').each(function(){$j(this).children('li').eq($counter).addClass('current');});
    });

    $j('a.prev_slide').click(function(){
      $j('#'+img_list[$counter]).removeClass('current');
      $j('div.nav_index ul').each(function(){$j(this).children('li').eq($counter).removeClass('current');});
      $counter-=1;
      if ($counter == -1) {$counter=img_list.length-1;}
      $j('#'+img_list[$counter]).addClass('current');
      $j('div.nav_index ul').each(function(){$j(this).children('li').eq($counter).addClass('current');});
    });
  };

  if ($j('#slideimages li').length == 1) {
    $j('div.prevnext_navigation').hide();
  }
/* MAKE IT - SLIDES end */

/* YOUTUBE VIDEOS start */
  var main_youtubemovie = $j('input#main_youtubemovieID').val();
  var subtitled_youtubemovie = $j('input#subtitled_youtubemovieID').val();

/* for main movie */
  swfobject.embedSWF(
    main_youtubemovie,
    'main_youtubemovie',
    '425','355','8', null, null,
    {allowScriptAccess: 'always', allowFullScreen: 'true', wmode: 'transparent'},
    {id: 'main_youtubemovie'}
  );

/* for subtitled movie */
  swfobject.embedSWF(
    subtitled_youtubemovie,
    'subtitled_youtubemovie',
    '425','355','8', null, null,
    {allowScriptAccess: 'always', allowFullScreen: 'true', wmode: 'transparent'},
    {id: 'subtitled_youtubemovie'}
  );

/* functionality for displaying movies */
  $j('.movie_subtitled').hide();
  $j('#subtitled_youtubemovie').hide();
  $j('#show_subtitled').click(function(){
    $j('.movie_main').hide();
    $j('.movie_subtitled').show();
    $j('#main_youtubemovie').hide();
    $j('#subtitled_youtubemovie').show();
  });
  $j('#show_main').click(function(){
    $j('.movie_subtitled').hide();
    $j('.movie_main').show();
    $j('#main_youtubemovie').show();
    $j('#subtitled_youtubemovie').hide();
  });
/* YOUTUBE VIDEOS end */

/* Display the TITLE attribute for Recipes big image */
  var recipe_alt = $j('div#recipes_content img').attr('alt');
  $j('div#recipes_content img').attr('title',recipe_alt);

}); /* -------------------- DOCUMENT READY END */


/* function for changing Article size */
function NewArticleSize(new_size){
  if (new_size == 'text_size_s'){$j('div#article').removeClass();}
  if (new_size == 'text_size_m'){$j('div#article').removeClass('articleLarge').addClass('articleMedium');}
  if (new_size == 'text_size_b'){$j('div#article').removeClass('articleMedium').addClass('articleLarge');}
}

function isValidEmailAddress(emailAddress){
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
}