var use_iframe = false;
var programme_url = base_url + 'site/show/';
var listing_url = base_url + 'site/listing/';
var send_a_friend_url = base_url + 'site/send_a_friend';
var prog_selection;
var select_genre = new Array;
var select_channel = new Array;
var listing_wrap;
var listing;
var current_time;
var load_hour;
var initial_difference;
var timeline_interval;
var time_li;
var time_first_active = false;
var time_prev;
var time_next;
var time_selection;
var popbox;
var tooltip_active = false;
var tooltip_interval;
var timelines_html = false;
var channels_regular_order;
var im = false;

$(document).ready(function () {
  listing_wrap = $('#listing_wrap');
  listing = $('#listing');

  if (listing_wrap.length) {
    listing_wrap.find('script').remove();
  }

  var now = new Date();
  load_hour = now.getHours();

  // show alert
  im = $('#alert');
  if (im.length) {
    var shown = readCookie('im') / 1;
    if (!shown) {
      createCookie('im', 1, 365);
      im.css('display', 'block');
    } else if (shown < 5) {
      createCookie('im', (shown + 1), 365);
      im.css('display', 'block');
    }
    im.click(function () {
      closeAlert();
      return false;
    });
  }

  // fix order if there are new channels
  var channels_in_cookie = readCookie('channel_order');
  if (channels_in_cookie) {
    channels_in_cookie = channels_in_cookie.split(',');
    var channels_in_html = listing.find('> li').not('.timeline');
    if (channels_in_cookie.length != channels_in_html.length) {
      channels_in_html.each(function () {
        var channel_name = $(this).attr('rel');
        if (jQuery.inArray(channel_name, channels_in_cookie) == -1) {
          channels_in_cookie.push(channel_name);
        }
      });
      createCookie('channel_order', channels_in_cookie.join(','), 365);
    }
  }

  initPositionTimelines();
  sortChannels();

  // films
  var films_wrap = $('#films_wrap');
  if (films_wrap.length) {
    $('.all_films').find('a').each(function () {
      var arr = $(this).attr('href').split('/');
      var id = arr[arr.length-2];
      $(this).click(function () {
        popProgramme(id);
        return false;
      });
    });
  }

  // tips
  var tips_wrap = $('#tips_wrap');
  if (tips_wrap.length) {
    tips_wrap.find('a').not('.rss').each(function () {
      var arr = $(this).attr('href').split('/');
      var id = arr[arr.length-2];
      $(this).click(function () {
        popProgramme(id);
        return false;
      });
    });
  }

  // store reference to #prog_selection
  prog_selection = $('#prog_selection');
  if (prog_selection.length) {
    // set show/hide for selection menu's
    prog_selection.find('h2').toggle(
      function (){
        var parent = $(this).parent();
        parent.find('ul').show();
        parent.addClass('foldout');
      },
      function (){
        var parent = $(this).parent();
        parent.find('ul').hide();
        parent.removeClass('foldout');
      }
    );

    // append onclicks to checkboxes
    prog_selection.find('ul:first').find(':checkbox').not(':last').click(parseGenreSelection);
    prog_selection.find('ul:first').find(':checkbox:last').click(resetGenreSelection);
    prog_selection.find('ul:last').find(':checkbox').not(':last').click(parseChannelSelection);
    prog_selection.find('ul:last').find(':checkbox:last').click(resetChannelSelection);

    var category_highlights = readCookie('category_highlights');
    if (category_highlights) {
      prog_selection.find('ul:first').find(':checkbox:last').attr('checked', false);
      category_highlights = category_highlights.split(',');
      prog_selection.find('ul:first').find(':checkbox').not(':last').each(function () {
        if (jQuery.inArray($(this).attr('name'), category_highlights) != -1) {
          $(this).attr('checked', true);
        } else {
          $(this).attr('checked', false);
        }
      });
      parseGenreSelection();
    }

    var visible_channels = readCookie('visible_channels');
    if (visible_channels) {
      prog_selection.find('ul:last').find(':checkbox:last').attr('checked', false);
      visible_channels = visible_channels.split(',');
      prog_selection.find('ul:last').find(':checkbox').not(':last').each(function () {
        if (jQuery.inArray($(this).attr('name'), visible_channels) != -1) {
          $(this).attr('checked', true);
        } else {
          $(this).attr('checked', false);
        }
      });
      parseChannelSelection();
    }

    // show #prog_selection
    prog_selection.show();
  }

  if (listing_wrap.length) {
    listing_wrap.css('display', 'block');
  }

  programmeClick();
  channelClick();

  // for the time selection
  time_selection = $('#time_selection');
  if (time_selection.length) {
    time_li = time_selection.find('li').not('.prev,.next');
    var i = 0;
    var prev;
    time_li.each(function () {
      i++;
      var link = $(this).find('a');
      var arr = $(this).attr('rel').split('/');
      var from = arr[(arr.length-1)];
      if (!time_first_active && $(this).attr('class') == 'active initial') {
        time_first_active = from;
      }
      var t;
      if (i == 23 || i == 24) {
        t = prev;
      } else {
        t = from;
        prev = t;
      }
      link.click(function () {
        showTimeFrom(t);
        return false;
      });
      $(this).attr('id', 'time_' + from.substr(8,2));
    });
    showTimePrevNext();
  }

  resetLink();
  overlaySize();
});

function closeAlert() {
  if (im.length) {
    createCookie('im', 99, 365);
    im.fadeOut('slow');
  }
}

function initPositionTimelines(nolinks) {
  timelines_html = '<li class="timeline">' + $('li.timeline:first').html() + '</li>';
}

function positionTimelines() {
  initPositionTimelines(true);
  $('li.timeline').remove();
  var channels = $('li.channel').not('.hidden');
  var i = 0;
  channels.each(function () {
    if (i == 0 || Math.round(i / 4) == (i / 4)) {
      $(this).before(timelines_html);
    }
    i++;
  });
}

function programmeClick() {
  if (listing_wrap.length && listing.length) {
    var initial_difference = load_hour - start_hour;
    if (initial_difference >= 0 && initial_difference <= 2) {
      listing_wrap.prepend('<div id="current_time"></div>');
      current_time = $('#current_time');
      positionCurrentTime();
      timeline_interval = setInterval("positionCurrentTime()", 60000);
      current_time.show();
    }
    listing.find('a').not('.earlier,.later').each(function () {
      var id = $(this).parent().attr('id').replace(/p_/, '');
      if (!is_mobile) {
        $(this).mouseover(function () {
          listing.sortableDisable();
          clearInterval(tooltip_interval);
          $('#tooltip').remove();
          if (!$(this).parent().parent().parent().hasClass('drag')) {
            var name = $(this).html();
            name = (name.length > 40) ? name.substr(0, 38)+'...' : name;
            var time = $(this).parent().find('span').html();
            var icon = $(this).parent().attr('rel');
            if (icon.indexOf(' ') != -1) {
              var arr = icon.split(' ');
              icon = arr[0];
            }
            $(this).parent().parent().append('<div id="tooltip" onmouseover="tooltip_active=true;listing.sortableDisable()" onmouseout="tooltip_active=false;listing.sortableEnable()"><div class="' + icon + '"></div><h4>' + name + '</h4><span>' + time.replace(/t_/, '') + '</span></div>');
            var tooltip = $('#tooltip');
            var left = nopx($(this).parent().css('left'));
            var width = nopx($(this).parent().css('width'));
            var offset = ((width / 2) + left) - 90;
            tooltip.css('left', offset+'px');
            tooltip.click(function () {
              popProgramme(id);
            });
            tooltip.show();
          }
        });
        $(this).mouseout(function () {
          listing.sortableEnable();
          tooltip_interval = setInterval("removeTooltip()", 1000);
        });
      }
    });
  }
}

function removeTooltip() {
  if (!tooltip_active) {
    clearInterval(tooltip_interval);
    $('#tooltip').remove();
  }
}

function nopx(string) {
  return string.replace(/px/, '') / 1;
}

function channelClick() {
  listing.find('h3').each(function () {
    $(this).prepend('<div class="drag"></div>');
    $(this).parent().prepend('<div class="close"></div>');
    $(this).parent().find('.close').click(function () {
      var li = listing.find('> li').not('.timeline');
      li.removeClass('drag hover inactive');
      showCurrentTime();
    });
    $(this).click(function () {
      var has_drag = $(this).parent().hasClass('drag');
      var li = listing.find('> li').not('.timeline');
      li.removeClass('drag hover');
      if (has_drag) {
        li.removeClass('inactive');
        showCurrentTime();
      } else {
        li.addClass('inactive');
        $(this).parent().addClass('drag');
        $(this).parent().removeClass('inactive');
        hideCurrentTime();
      }
    });
    $(this).mouseover(function () {
      var has_drag = $(this).parent().hasClass('drag');
      if (has_drag) {
        $(this).css('cursor', 'move');
      } else {
        $(this).css('cursor', 'pointer');
      }
      var parent_class = $(this).parent().attr('class');
      if (parent_class != 'drag' && parent_class != 'inactive') {
        $(this).parent().addClass('hover');
      }
    });
    $(this).mouseout(function () {
      $(this).css('cursor', '');
      $(this).parent().removeClass('hover');
    });
  });
  listing.sortable({
    items:'li.channel',
    start:function () {
      hideCurrentTime();
      var channel = $(this).attr('rel');
      listing.find('> li').not('.timeline').each(function () {
        if ($(this).attr('rel') == channel) {
          $(this).removeClass('inactive');
          $(this).addClass('drag');
        } else {
          $(this).removeClass('drag hover');
          $(this).addClass('inactive');
        }
      });
    },
    update:function () {
      positionTimelines();
      storeChannelOrder();
      var li = listing.find('> li').not('.timeline');
      li.removeClass('drag hover inactive');
      showCurrentTime();
    }
  });
  listing.sortableEnable();
}

function storeChannelOrder() {
  var order = new Array();
  listing.find('> li').not('.timeline').each(function () {
    order.push($(this).attr('rel'));
  });
  createCookie('channel_order', order.join(','), 365);
}

function sortChannels() {
  channels_regular_order = listing_wrap.html();
  var order = readCookie('channel_order');
  if (order) {
    initPositionTimelines();
    var channels = new Object();
    listing.find('> li').not('.timeline').each(function () {
      var rel = $(this).attr('rel');
      channels[rel] = '<li class="' + $(this).attr('class') + '" rel="' + rel + '">' + $(this).html() + '</li>';
    });
    var arr = order.split(',');
    listing.find('*').remove();
    for (i=0; i<arr.length; i++) {
      listing.append(channels[arr[i]]);
    }

    var channels = $('li.channel').not('.hidden');
    var i = 0;
    channels.each(function () {
      if (i == 0 || Math.round(i / 4) == (i / 4)) {
        $(this).before(timelines_html);
      }
      i++;
    });
  }
}

function resetLink() {
  var l = $('#reset_order');
  if (!l.length) {
    listing_wrap.after('<a href="#" id="reset_order" onclick="setToDefaults(); return false">&gt; ' + lang.reset_values + '</a>');
  }
}

function setToDefaults() {
  eraseCookie('channel_order');
  listing_wrap.html(channels_regular_order);
  listing_wrap = $('#listing_wrap');
  listing = $('#listing');
  positionTimelines();
  programmeClick();
  channelClick();
  resetChannelSelection();
  resetGenreSelection();
  resetLink();
}

function showTimeFrom(time) {
  time_first_active = time;
  time_li.each(function () {
    $(this).removeClass('active');
  });

  time_1 = time.substr(8,2) / 1;
  $('#time_'+time_1).addClass('active');
  time_2 = ((time_1 + 1) > 23) ? ((time_1 + 1) - 24) : time_1 + 1;
  time_3 = ((time_1 + 2) > 23) ? ((time_1 + 2) - 24) : time_1 + 2;
  time_1 = (time_1 < 10) ? '0'+time_1 : time_1;
  time_2 = (time_2 < 10) ? '0'+time_2 : time_2;
  time_3 = (time_3 < 10) ? '0'+time_3 : time_3;
  $('#time_'+time_1+', #time_'+time_2+', #time_'+time_3).addClass('active');

  showTimePrevNext();
  showListing(time);
}

function showTimePrevNext() {
  time_selection.find('li.prev, li.next').remove();
  var date = time_first_active.substr(0,8) / 1;
  var time = time_first_active.substr(8,2) / 1;
  if (time != time_hour) {
    var newtime = ((time-1) < 0) ? (time-1)+24 : time-1;
    newtime = (newtime < 10) ? '0'+newtime : newtime;
    $('#time_'+((time < 10) ? '0'+time : time)).before('<li class="prev" onclick="showTimeFrom(\'' + date + newtime + '\'); return false"><a href="#">' + lang.earlier + '</a></li>');
  }
  if (time != (time_hour-3)) {
    var id = ((time+2) > 23) ? ((time+2)-24) : time+2;
    var newtime = ((time+1) > 23) ? (time+1)-24 : time+1;
    newtime = (newtime < 10) ? '0'+newtime : newtime;
    $('#time_'+(id = (id < 10) ? '0'+id : id)).after('<li class="next" onclick="showTimeFrom(\'' + date + newtime + '\'); return false"><a href="#">' + lang.later + '</a></li>');
  }
}

function showListing(from) {
  var h = body_height();
  $('html').css('height', h+'px');
  showLoading();
  listing_wrap.css('display', 'none');
  if (listing_wrap) {
    listing_wrap.load(listing_url+from, null, function () {
      start_hour = from.substr(8,2);
      listing_wrap = $('#listing_wrap');
      listing = $('#listing');
      sortChannels();
      programmeClick();
      channelClick();
      parseChannelSelection();
      resetLink();
      $('#listload').remove();
      listing_wrap.css('display', 'block');
      $('html').css('height', '');
      parseGenreSelection();
    });
  }
}

function showLoading() {
  listing_wrap.after('<div id="listload"><img src="static/images/loading2.gif" alt="loading" /> ' + lang.loading + '...</div>');
}

// start popbox
function popProgramme(id) {
  showPopbox();
  showProgramme(id);
}

function overlaySize() {
  var overlay = $('#overlay');
  if (overlay.length) {
    var height = body_height();
    overlay.css('height', height+'px');
  }
}

function showPopbox(id) {
  var viewport = vp();
  var offset = os();
  $('#tooltip').remove();
  if (typeof document.body.style.maxHeight === "undefined") {
    $('html').css('overflow', 'hidden');
  }
  $('body').append('<div id="overlay"></div>');
  var overlay = $('#overlay');
  var height = body_height();
  overlay.css('height', height+'px');
  detectMac() ? overlay.addClass('overlay_mac') : overlay.addClass('overlay');
  overlay.click(hidePopbox);
  document.onkeydown = function (e) {
    keycode = (e == null) ? event.keyCode : keycode = e.which;
    if (keycode == 27) {
      hidePopbox();
    }
  };
  $('body').append('<div id="popbox"></div>');
  var popbox = $('#popbox');
  if (use_iframe) {
    popbox.append('<iframe id="popbox_iframe" frameborder="0"></iframe>');
  } else {
    popbox.css({padding:'6px', width:'732px', height:'399px'});
  }
  var left = (viewport[0] - 744) / 2;
  left = (left < 0) ? 0 : left;
  var top = ((viewport[1] - 411) / 2) + offset[1];
  top = (top < 0) ? 0 : top;
  popbox.css('left', left + 'px');
  popbox.css('top', top + 'px');

  if (detectMac()) {
    popbox.show();
    if (id) {
      showProgramme(id);
    }
  } else {
    overlay.css('opacity', 0).fadeTo('fast', 0.75, function () {
      popbox.fadeIn('fast', function () {
        if (id) {
          showProgramme(id);
        }
      });
    });
  }
}

function hidePopbox() {
  document.onkeydown = '';
  $('#popbox').fadeOut('fast');
  $('#overlay').fadeOut('fast', function () {
    $('#popbox,#hideselect,#overlay').remove();
    $('html').css('overflow', '');
  });
}

function showProgramme(id, loader) {
  if (!loader) {
    loader = false;
  }
  if (use_iframe) {
    var popbox_iframe = $('#popbox_iframe');
    if (popbox_iframe.length) {
      popbox_iframe.attr('src', programme_url + id);
    }
  } else {
    popbox = $('#popbox');
    if (popbox.length) {
      popbox.html('');
      if (loader) {
        popbox.prepend('<div id="popbox_load">bezig met laden</div>');
      }
      popbox.load(programme_url + id, null, function () {
        parsePopbox(id);
        $('#popbox_load').remove();
      });
    }
  }
}

function parsePopbox(prog_id) {
  popbox = $('#popbox');
  popbox.prepend('<a href="#" class="close" onclick="hidePopbox(); return false">' + lang.close + '</a>');
  $('p.prevnext,table').find('a').each(function () {
    var arr = $(this).attr('href').split('/');
    var id = arr[arr.length-2];
    $(this).click(function () {
      showProgramme(id, false);
      return false;
    });
  });
  $('#mail').append('<a href="#" class="arrow" onclick="sendFriend(' + prog_id + '); return false">' + lang.mail_to + '</a>');
}

function sendFriend(id) {
  $('#program_info').append('<div id="sendfriend"></div>');
  var sendfriend = $('#sendfriend');
  sendfriend.load(send_a_friend_url+'/'+id);
}

function cancelSendFriend() {
  $('#sendfriend').remove();
}

function sendFriendForm() {
  var to_name = $('#to_name');
  var to_mail = $('#to_mail');
  var sender = $('#sender');
  if (!to_name || to_name == '' || to_name == 'Naam' || !checkEmail(to_mail[0].value) || !checkEmail(sender[0].value)) {
    alert(lang.check_input)
  } else {
    var arr = $('#friendform').serialize();
    $.post(send_a_friend_url, arr, function (data) {
      $('#sendfriend').html(data);
    });
  }
}

function friendInput(el) {
  el.value = '';
  el.className = '';
}

function detectMac() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('firefox') != -1) {
    return true;
  }
}
// end popbox

function t(time) {
  title = time.find('span').html();
  if (title) {
    title = title.replace(/t_/, '');
    var arr = title.split('-');
    return [(arr[0] / 1),(arr[1] / 1)];
  } else {
    return false;
  }
}

function positionCurrentTime() {
  var now = new Date();
  var diff = now.getHours() - start_hour;
  if (!current_time) {
    current_time = $('#current_time');
  }
  if (current_time.length && diff >= 0 && diff <= 2) {
    var position = (diff * 180) + 141 + (now.getMinutes() * 3);
    current_time.css('left', position+'px');
    current_time.css('height', ($('#listing_wrap').height()-32)+'px');
    if (select_genre.length == 0) {
      highlightNow(true);
    }
  } else {
    clearInterval(timeline_interval);
    hideCurrentTime();
    if (select_genre.length == 0) {
      removeHighlights();
    }
  }
}

function hideCurrentTime() {
  current_time = $('#current_time');
  if (current_time.length) {
    current_time.hide();
  }
}

function showCurrentTime() {
  current_time = $('#current_time');
  if (current_time.length) {
    current_time.show();
  }
}

function removeHighlights() {
  listing.find('li').each(function () {
    var classname = $(this).attr('class');
    if (classname) {
      if (classname == 'active') {
        $(this).removeClass('active')
      } else if (classname.indexOf('_active') != -1) {
        $(this).addClass(classname.replace(/_active/, ''));
        $(this).removeClass(classname);
      }
    }
  });
}

function addHighlight(li) {
  var classname = li.attr('class');
  if (!classname) {
    li.addClass('active');
  } else if (classname != 'active' && classname.indexOf('_active') == -1) {
    li.addClass(classname + '_active');
    li.removeClass(classname);
  }
}

function removeHighlight(li) {
  var classname = li.attr('class');
  if (classname) {
    if (classname == 'active') {
      li.removeClass('active')
    } else if (classname.indexOf('_active') != -1) {
      li.addClass(classname.replace(/_active/, ''));
      li.removeClass(classname);
    }
  }
}

function highlightNow() {
  var now = new Date();
  var hour = (now.getHours() < 10) ? '0' + now.getHours() : now.getHours();
  var minutes = (now.getMinutes() < 10) ? '0' + now.getMinutes() : now.getMinutes();
  var timestamp = (now.getHours() + '.' + minutes) / 1;
  listing.find('ul').each(function () {
    var ul = $(this);
    ul.find('li').each(function () {
      var time = t($(this));
      if (time && time[0] <= timestamp && (time[1] > timestamp || time[1] < time[0])) {
        addHighlight($(this));
      } else {
        removeHighlight($(this));
      }
    });
  });
}

function parseGenreSelection() {
  select_genre = new Array;
  var selected = new Array();
  prog_selection.find('ul:first').find(':checkbox').not(':last').each(function (){
    var name = $(this).attr('name');
    if (name && $(this).attr('checked')) {
      select_genre.push(name);
      selected.push(name);
    }
  });
  var cb = prog_selection.find('ul:first').find(':checkbox:last');
  if (select_genre.length == 0) {
    resetGenreSelection();
  } else {
    cb.attr('checked', false);
    createCookie('category_highlights', selected.join(','), 365);
  }
  highlightGenreSelection();
  positionCurrentTime();
}

function highlightGenreSelection() {
  listing.find('li').each(function () {
    var title = $(this).attr('rel');
    var parsed = false;
    if (title) {
      var classname = $(this).attr('class');
      var arr = title.split(' ');
      for (i=0; i<arr.length; i++) {
        if (jQuery.inArray(arr[i], select_genre) != -1) {
          parsed = true;
          (classname && classname.indexOf('active') == -1) ? $(this).attr('class', classname + '_active') : $(this).addClass('active');
        }
      }
      if (classname && !parsed) {
        if (classname == 'active') {
          $(this).removeClass('active')
        } else if (classname.indexOf('_active') != -1) {
          $(this).addClass(classname.replace(/_active/, ''));
          $(this).removeClass(classname);
        }
      }
    }
  });
}

function resetGenreSelection(init) {
  eraseCookie('category_highlights');
  select_genre = new Array;
  var ul = prog_selection.find('ul:first');
  ul.find(':checkbox').not(':last').attr('checked', false);
  ul.find(':checkbox:last').attr('checked', true);
  if (init != true) {
    highlightNow();
  }
}

function parseChannelSelection() {
  select_channel = new Array;
  var selected = new Array();
  prog_selection.find('ul:last').find(':checkbox').not(':last').each(function (){
    var name = $(this).attr('name');
    if (name && $(this).attr('checked')) {
      select_channel.push(name);
      selected.push(name);
    }
  });
  var cb = prog_selection.find('ul:last').find(':checkbox:last');
  if (select_channel.length == 0) {
    resetChannelSelection();
  } else {
    cb.attr('checked', false);
    createCookie('visible_channels', selected.join(','), 365);
    highlightChannelSelection();
  }
  positionTimelines();
  positionCurrentTime();
}

function highlightChannelSelection() {
  if (select_channel.length > 0) {
    $('#listing > li').each(function () {
      $(this).removeClass('hidden');
      var title = $(this).attr('rel');
      if (jQuery.inArray(title, select_channel) == -1) {
        $(this).addClass('hidden');
      }
    });
  }
}

function resetChannelSelection(init) {
  eraseCookie('visible_channels');
  select_channel = new Array;
  var ul = prog_selection.find('ul:last');
  ul.find(':checkbox').not(':last').attr('checked', false);
  ul.find(':checkbox:last').attr('checked', true);
  $('#listing > li').removeClass('hidden');
  if (init != true) {
    highlightNow();
  }
  positionTimelines();
}

function vp() {
  var x, y;

  if (self.innerHeight) {
    x = self.innerWidth;
    y = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) {
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  } else if (document.body) {
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }

  return [x, y];
}

function os() {
  var x, y;

  if (self.pageYOffset) {
    x = self.pageXOffset;
    y = self.pageYOffset;
  } else if (document.documentElement && document.documentElement.scrollTop) {
    x = document.documentElement.scrollLeft;
    y = document.documentElement.scrollTop;
  } else if (document.body) {
    x = document.body.scrollLeft;
    y = document.body.scrollTop;
  }

  return [x, y];
}

function body_height() {
  if (document.documentElement.clientHeight > document.documentElement.scrollHeight) {
    return document.documentElement.clientHeight;
  } else {
    return document.documentElement.scrollHeight;
  }
}

function checkEmail(emailStr) {
  var emailPat = /^(.+)@(.+)$/;
  var specialChars = "\\(\\)><@,;:\\\\\\\"\\[\\]";
  var validChars = "\[^\\s" + specialChars + "\]";
  var atom = validChars + '+';
  var word="(" + atom + ")";
  var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
  var matchArray = emailStr.match(emailPat);

  if (matchArray == null) {
    return false;
  }

  var user = matchArray[1];
  var domain = matchArray[2];

  for (i = 0; i < user.length; i++) {
    if (user.charCodeAt(i) > 127) {
      return false;
    }
  }

  for (i = 0; i < domain.length; i++) {
    if (domain.charCodeAt(i) > 127) {
      return false;
    }
  }

  if (user.substring(0,1) == '.' || user.substring((user.length-1),user.length) == '.') {
    return false;
  }

  if (user.match(userPat) == null) {
    return false;
  }

  var atomPat = new RegExp("^" + atom + "$");
  var domArr = domain.split(".");
  var len=domArr.length;
  for (i = 0; i < len; i++) {
    if (domArr[i].search(atomPat) == -1) {
      return false;
  }
  }

  if (len < 2) {
    return false;
  }

  return true;
}

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 {
    var 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;
}

function eraseCookie(name) {
  createCookie(name, '', -1);
}
