var localStrings = {};
var httpRequest = null;
var deletingComments = new Array();

if (window.XMLHttpRequest)
{
  httpRequest = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
  try
  {
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  }    
  catch (CatchException)
  {
    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  }
}

function implode (glue, pieces) {
    // Joins array elements placing glue string between items and return one string
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/implode
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    
    var i = '', retVal='', tGlue='';
    
    if (arguments.length === 1)
    {
        pieces = glue;
        glue = '';
    }
    
    if (typeof(pieces) === 'object')
    {
        if (pieces instanceof Array)
        {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else
    {
        return pieces;
    }
}

function arrayFinder(what, where)
{
    var a=-1;
    var ret;
    
    for(var i=0; i < where.length; i++)
    {
        if(what == where[i])
        {
            a=i;
            break;
        }
    }
    return a;
}


function openInClient(url)
{
  window.opener.document.cookie = "OPEN_ITEMS_IN_CLIENT=1;path=/";
  var loc = window.opener.location.href;
  window.opener.location.href = url;
  window.opener.location.href = loc;

  window.close();
}


function showDialog(url, id, w, h)
{
  var l = (screen.width - w) / 2;
  var t = (screen.height - h) / 2;

  var parent = (window.opener ? window.opener : window);
  var wnd = null;

  try
  {
    wnd = parent.open(url, id, "toolbar=no,location=no,directories=no,menubar=no,resizable=no,width="+w+",height="+h+",left="+l+",top="+t);
  }
  catch(e)
  {
    try
    {
      if (parent == window.opener)
        wnd = window.open(url, id, "toolbar=no,location=no,directories=no,menubar=no,resizable=no,width="+w+",height="+h+",left="+l+",top="+t);
    }
    catch(e) {}
  }

  if (wnd)
    wnd.focus();
  else
    alert(localStrings.couldntOpenPopup);
}


function getClient(url)
{
  showDialog(url, "yuPlayGetClientWnd", 780, 580);
}


function downloadClient(url)
{
  window.opener.location.href = url;
  window.close();
}


function toggleElementVis(comm_id)
{
  var elem = document.getElementById(comm_id);
  elem.style.display = elem.style.display ? '' : 'none';
}


function delItem(idx, title, confirm)
{
  if (window.confirm(confirm + " \"" + title + "\"?"))
    window.location.href="/editlink.php?id=" + idx + "&action=del";
}

function selectDelComment(commentId)
{
    var commentArrIndx;
    if(deletingComments.length > 0)
    {
        commentArrIndx = arrayFinder(commentId, deletingComments);
        if(commentArrIndx > -1)
        {
            $j('#comment_div_'+commentId).css("background-color", "");
            deletingComments.splice(deletingComments.indexOf(commentId), 1);
        }
        else
        {
            deletingComments[deletingComments.length] = commentId;
            $j('#comment_div_'+commentId).css("background-color", "#FFCC99");
        }

    }
    else
    {
        deletingComments[deletingComments.length] = commentId;
        $j('#comment_div_'+commentId).css("background-color", "#FFCC99");

    }

    if(deletingComments.length == 0)
      $j('#del_comments_button').hide();
    else
      $j('#del_comments_button').show();
}

function delComment(confirm, url)
{
  if (window.confirm(confirm))
    window.location.href=url;
}

function delSelComments(confirm, url)
{
  if (window.confirm(confirm))
      window.location.href=url+'&comments_ids='+implode(',', deletingComments)+'&del=1';
}

function showScreenshot(guid, file)
{
  var url = "/screenshot.php?guid=" + guid + "&scrn=" + file;
  showDialog(url, "yuPlayScreenshotWnd", 900, 700);
}


function allScreenshots(guid)
{
  var url = "/screenshots.php?guid=" + guid;
  showDialog(url, "yuPlayScreenshotWnd", 900, 700);
}


var paymentWndParent = null;


function showDropdown(parent, payment)
{
  var ret = false;
  var elem = document.getElementById("PAYMENT_WND");

  if (elem && elem.style.display == "none" || paymentWndParent != parent)
  {
    elem.style.display = "";

    if (parent)
    {
      var x = 0, y = 0;
      var cur = parent;
      while (cur)
      {
        x += cur.offsetLeft;
        y += cur.offsetTop;
        cur = cur.offsetParent;
      }
      
      elem.style.left = x;
      elem.style.top = y + parent.offsetHeight - 2;
      elem.style.width = parent.offsetWidth;
    }

    var p = document.getElementById("PAYMENT_CONTENT");
    var d = document.getElementById("DOWNLOAD_CONTENT");
    var a = document.getElementById("ACT_ONLY_CONTENT");

    if (p)
      p.style.display = payment == 1 ? "" : "none";

    if (d)
      d.style.display = payment == 0 ? "" : "none";

    if (a)
      a.style.display = payment == 2 ? "" : "none";

    ret = true;
  }

  paymentWndParent = parent ? parent : document;

  return ret;
}


function showPaymentWnd(parent, item_id, payment,
                        yum, yum_link,
                        yam, yam_link,
                        wm, wm_link,
                        sms, sms_link,
                        om, om_link,
                        visa, visa_link,
                        beeline, beeline_link,
                        qiwi, qiwi_link,
                        pp, pp_link,
                        pp_eur, pp_link_eur,
                        pp_visa_eur, pp_visa_link_eur,
                        platnosci, platnosci_link,
                        activation)
{
  if (showDropdown(parent, payment) && parent)
  {
    if (payment == 1)
    {
      //set item id
      var forms = new Array(
        { "form_id": "ShopForm", "item_id": "CustItemID", "val":yam },
        { "form_id": "ShopFormWm", "item_id": "WMItemID", "val":wm },
        { "form_id": "ShopFormOM", "item_id": "OMItemID", "val":om },
        { "form_id": "ShopFormVisa", "item_id": "VisaItemID", "val":visa }
      );

      for (var i = 0; i < forms.length; ++i)
      {
        var f = document.getElementById(forms[i].form_id);
        if (f)
        {
          f.Sum.value = forms[i].val;
          f[forms[i].item_id].value = item_id;
        }
      }

      //set prices
      var payLink;
      var cntElem;

      var prices = new Array(
        { "cnt_id": "YUM_COUNT", "cnt": yum, "link_id": "YUM_LINK", "link": yum_link },
        { "cnt_id": "YAM_COUNT", "cnt": yam, "link_id": "YAM_LINK", "link": yam_link },
        { "cnt_id": "WM_COUNT", "cnt": wm, "link_id": "WM_LINK", "link": wm_link },
        { "cnt_id": "OM_COUNT", "cnt": om, "link_id": "OM_LINK", "link": om_link },
        { "cnt_id": "SMS_COUNT", "cnt": sms, "link_id": "SMS_LINK", "link": sms_link },
        { "cnt_id": "VISA_COUNT", "cnt": visa, "link_id": "VISA_LINK", "link": visa_link },
        { "cnt_id": "BEELINE_COUNT", "cnt": beeline, "link_id": "BEELINE_LINK", "link": beeline_link },
        { "cnt_id": "QIWI_COUNT", "cnt": qiwi, "link_id": "QIWI_LINK", "link": qiwi_link },
        { "cnt_id": "PP_COUNT", "cnt": pp, "link_id": "PP_LINK", "link": pp_link },
        { "cnt_id": "PP_EUR_COUNT", "cnt": pp_eur, "link_id": "PP_EUR_LINK", "link": pp_link_eur },
        { "cnt_id": "PP_EUR_VISA_COUNT", "cnt": pp_visa_eur, "link_id": "PP_EUR_VISA_LINK", "link": pp_visa_link_eur },
        { "cnt_id": "PLATNOSCI_COUNT", "cnt": platnosci, "link_id": "PLATNOSCI_LINK", "link": platnosci_link }
      );

      for (var i = 0; i < prices.length; ++i)
      {
        var price = prices[i];

        cntElem = document.getElementById(price.cnt_id);
        if (cntElem)
          cntElem.innerHTML = price.cnt;

        payLink = document.getElementById(price.link_id);
        if (payLink)
          payLink.href = price.link;
      }

      document.getElementById("ACTIVATION_LINK").style.display = activation ? "" : "none";
    }
    else if (!payment)
    {
      var links = new Array(
        { "link_id": "YUPLAY_LINK", "link": "/downloader.php?id=" + item_id },
        { "link_id": "TORRENT_LINK", "link": "/torrent.php?id=" + item_id },
        { "link_id": "HTTP_LINK", "link": "/get_http.php?id=" + item_id }
      );

      for (var i = 0, linkData, link; i < links.length; ++i)
      {
        linkData = links[i];
        link = document.getElementById(linkData.link_id);

        if (link)
          link.href = linkData.link;
      }
    }
  }
}


function confirmArea(area, id, payment)
{
  var url = "/area.php?area=" + area + "&id=" + id + "&payment=" + payment;
  showDialog(url, "yuPlayAreaConfirmWnd", 700, 240);
}


function cinemaEULA(id, payment)
{
  var url = "/cinema_eula.php?id=" + id + "&payment=" + payment;
  showDialog(url, "yuPlayCinemaEULAWnd", 700, 500);
}

function customEULA(id, payment)
{
  var url = "/item_eula.php?id=" + id + "&payment=" + payment;
  showDialog(url, "yuPlayItemEULAWnd", 700, 500);
}


function payYam(external)
{
  var yaForm = external ?
    window.opener.document.getElementById("ShopForm") :
    document.getElementById("ShopForm");

  if (parseFloat(yaForm.Sum.value) >= 1.0 && parseInt(yaForm.CustItemID.value) >= 0)
    yaForm.submit();
}


function payWm(external)
{
  var wmForm = external ?
    window.opener.document.getElementById("ShopFormWm") :
    document.getElementById("ShopFormWm");

  if (parseFloat(wmForm.Sum.value) >= 1.0 && parseInt(wmForm.WMItemID.value) >= 0)
    wmForm.submit();
}


function payVisa(external)
{
  var visaForm = external ?
    window.opener.document.getElementById("ShopFormVisa") :
    document.getElementById("ShopFormVisa");

  visaForm.submit();
}


function payOM(external)
{
  var omForm = external ?
    window.opener.document.getElementById("ShopFormOM") :
    document.getElementById("ShopFormOM");

  if (parseFloat(omForm.Sum.value) >= 1.0 && parseInt(omForm.OMItemID.value) >= 0)
    omForm.submit();
}


function hidePaymentWndTimeout()
{
  if (!paymentWndParent)
  {
    var elem = document.getElementById("PAYMENT_WND");
    elem.style.display = "none";
  }
}


function hidePaymentWnd()
{
  paymentWndParent = null;
  setTimeout("hidePaymentWndTimeout()", 800);
}


var playerId = null;
var playerHTML;

function playMp3(id, mp3)
{
  if (playerId)
    document.getElementById(playerId).innerHTML = playerHTML;

  playerId = id;

  var el = document.getElementById(id);
  playerHTML = el.innerHTML;

  var playUrl = "http://yuplay.ru/swf/mediaplayer.swf";
  var mp3Url =  "http://files.yuplay.ru/mp3/" + mp3;
  var playW = 300;
  var playH = 20;

  el.innerHTML = '<object type="application/x-shockwave-flash" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" data="'+playUrl+'" height="'+playH+'" width="'+playW+'"><param name="wmode" value="transparent" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+playUrl+'" /><param name="flashvars" value="file='+mp3Url+'&amp;autostart=1&amp;usefullscreen=0&amp;width='+playW+'&amp;height='+playH+'" /><embed height="'+playH+'" width="'+playW+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" src="'+playUrl+'" flashvars="file='+mp3Url+'&autostart=1&usefullscreen=0&width='+playW+'&height='+playH+'" /></object>';
}


function sendMobileId(edit, url)
{
  if (edit.value.length)
  {
    window.opener.location.href = url + "?id=" + edit.value;
    window.close();
  }
}


function setVoters(voters_html, voters_id)
{
  if (typeof(voters_html) == "string")
  {
    var votersEl = document.getElementById(voters_id);

    if (votersEl)
      votersEl.innerHTML = voters_html;
  }
}


function getItemVoters(id, vote)
{
  var votersId = "VOTERS_" + vote;
  var votersEl = document.getElementById(votersId);
  var linkEl = document.getElementById("VOTERS_DESC_" + vote);

  if (votersEl)
  {
    if (votersEl.style.display.length)
    {
      votersEl.style.display = "";

      if (!votersEl.hasChildNodes() && httpRequest)
      {
        httpRequest.abort();
        eval("httpRequest.onreadystatechange = function(){" +
          "if (httpRequest.readyState == 4 && httpRequest.status == 200)" +
            "setVoters(httpRequest.responseText, '"+votersId+"');}");

        httpRequest.open("GET", "yuplay/get_voters.php?id=" + id + "&vote=" + vote+"&rand="+Math.random(), true);
        httpRequest.send(null);
      }
    }
    else
      votersEl.style.display = "none";
  }

  if (linkEl)
    if (linkEl.className == "votes_link")
      linkEl.className = "votes_link_open";
    else
      linkEl.className = "votes_link";
}

function fastReg(form, text)
{
  if (!form.username.value.match(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
  {
    alert(text);
    return false;
  }

  form.submit();
  return true;
}


function onCCChange(form)
{
  var enable = 
    form.card_owner.value.match(/^[a-z\.\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u017F ]+ [a-z\.\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\u0100-\u017F ]+$/i) &&
    form.card_num.value.match(/^[0-9]{13,16}$/) &&
    form.card_ccv.value.match(/^[0-9]{3,4}$/) &&
    form.card_city.value.length &&
    form.card_address.value.length &&
    form.card_zip.value.length;

  if (enable)
    form.card_submit.removeAttribute("disabled");
  else
    form.card_submit.setAttribute("disabled", 1);
}


function stopEvent(evt)
{
  if (evt.stopPropagation)
    evt.stopPropagation();
  else
    evt.cancelBubble = false;

  if (evt.preventDefault)
    evt.preventDefault();

  evt.returnValue = false;
}

var qiwiFocus = null;
var qiwiFocusLeft = false;
function onQiwiKeyDown(evt)
{
  evt = evt || window.event;
  var handle = false;

  if ((evt.keyCode >= 0x41 && evt.keyCode <= 0x5A) || evt.keyCode == 0xC0 ||
    (evt.keyCode >= 0xBC && evt.keyCode <= 0xBF) || evt.keyCode == 0x3B ||
    (evt.keyCode >= 0x6A && evt.keyCode <= 0x6F) || (evt.keyCode >= 0xDB && evt.keyCode <= 0xDE))
      handle = true;

  if (handle)
  {
    stopEvent(evt);
    return false;
  }

  var edit = null;
  if (evt.target)
    edit = evt.target;
  else if (evt.srcElement)
    edit = evt.srcElement;

  if (!edit)
    return true;

  var caretPos = -1;
  if (document.selection)
  {
    var sel = document.selection.createRange();

    sel.moveStart("character", -edit.value.length);
    caretPos = sel.text.length;
  }
  else if (edit.selectionStart || edit.selectionStart == '0')
    caretPos = edit.selectionStart;

  if (caretPos < 0)
    return;

  var inputs = new Array(
    { "name":"id1", "left":null, "right":edit.form.id2 },
    { "name":"id2", "left":edit.form.id1, "right":edit.form.id3 },
    { "name":"id3", "left":edit.form.id2, "right":edit.form.id4 },
    { "name":"id4", "left":edit.form.id3, "right":null }
  );

  var moveRight =
    (evt.keyCode >= 0x30 && evt.keyCode <= 0x39 || evt.keyCode == 0x27) &&
    (caretPos > 0 && caretPos == edit.getAttribute("maxlength") - 1);

  var moveLeft =
    (evt.keyCode == 0x25 || evt.keyCode == 0x08) && caretPos == 0;

  if (moveRight || moveLeft)
    for (var i = 0; i < inputs.length; ++i)
      if (inputs[i].name == edit.name)
      {
        qiwiFocus = moveRight ? inputs[i].right : inputs[i].left;
        qiwiFocusLeft = moveLeft;
        setTimeout("focusQiwi()", 0);
        break;
      }


  return true;
}


function focusQiwi()
{
  if (qiwiFocus)
  {
    qiwiFocus.focus();

    if (qiwiFocusLeft)
    {
      if (document.selection)
      {
        var sel = document.selection.createRange();
        sel.moveStart("character", -qiwiFocus.value.length);

        sel.moveStart("character", qiwiFocus.value.length);
        sel.moveEnd("character", 0);
        sel.select();
      }
      else if (qiwiFocus.setSelectionRange)
        qiwiFocus.setSelectionRange(qiwiFocus.value.length, qiwiFocus.value.length);
    }
  }
}

function onQiwiKeyUp(edit)
{
  var enable = 
    edit.form.id1.value.match(/^[0-9]{3}$/) &&
    edit.form.id2.value.match(/^[0-9]{3}$/) &&
    edit.form.id3.value.match(/^[0-9]{2}$/) &&
    edit.form.id4.value.match(/^[0-9]{2}$/);

  if (enable)
    edit.form.qiwi_submit.removeAttribute("disabled");
  else
    edit.form.qiwi_submit.setAttribute("disabled", 1);
}

var httpReqArray = {};
function getPurchData(url, progress, link, set_el)
{
  link.parentNode.innerHTML = "<img src='/templates/yuplay2/img/" + progress + ".gif' />";
  var httpReq = null;

  if (window.XMLHttpRequest)
  {
    httpReq = new XMLHttpRequest();
  }
  else if (window.ActiveXObject)
  {
    try
    {
      httpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }    
    catch (CatchException)
    {
      httpReq = new ActiveXObject("Msxml2.XMLHTTP");
    }
  }

  if (httpReq)
  {
    var httpId = Math.random().toString();
    var httpIdEl = httpId + "_EL";
    httpReqArray[httpId] = httpReq;
    httpReqArray[httpIdEl] = set_el;

    httpReq.open("GET", url, true);

    eval("httpReq.onreadystatechange = function(){" +
      "if (httpReqArray['" + httpId + "'].readyState == 4){" +
        "if (httpReqArray['" + httpId + "'].status == 200)" +
          "httpReqArray['" + httpIdEl + "'].innerHTML = httpReqArray['" + httpId + "'].responseText;" +
      "httpReqArray['" + httpId + "'] = httpReqArray['" + httpIdEl + "'] = null;}}"
    );

    httpReq.send(null);
  }
}

function showAppPurchases(link, id, sec)
{
  var el = link.parentNode;
  while (el.tagName != "DIV")
    el = el.parentNode;

  getPurchData("user.php?view=purch_data&id=" + id + "&rand=" + Math.random(),
    sec ? "progress2" : "progress", link, el);
}

function showPurch(type, text, first)
{
	var s	= $j( '#PURCH_' + type + '_link > a' ).text();

	$j( '#PURCH_' + type + '_link > a' ).unbind( "click" );
	$j( '#PURCH_' + type + '_link > a' )
		.bind( "click", function(event) {
			hidePurch( type, s );
			return false;
		})
		.html( text );
	$j( '#PURCH_' + type ).attr( 'class', 'votes_link_open' );

	if( true == first ){
		$j( '#PURCH_' + type + '_c' ).html( '<div class="c"><img src="/templates/yuplay2/img/progress.gif"></div>' );

		$j.ajax({
			type: "GET",
			url: "/user.php?view=purch_type&type=" + type + "&rand=" + Math.random(),
			success: function(data){
				$j( '#PURCH_' + type + '_c' ).html( data );
			}
		});
	}
	else
	{
		$j( '#PURCH_' + type + '_c' ).css( 'display', 'block' );
	}
}

function hidePurch(type, text)
{
	var s	= $j( '#PURCH_' + type + '_link > a' ).text();

	$j( '#PURCH_' + type + '_link > a' ).unbind( "click" );
	$j( '#PURCH_' + type + '_link > a' )
		.bind( "click", function(event) {
			showPurch( type, s, false );
			return false;
		})
		.html( '<b>' + text + '</b>' );
		
	$j( '#PURCH_' + type + '_link' ).attr( 'class', 'votes_link' );

	$j( '#PURCH_' + type + '_c' ).css( 'display', 'none' );
}

function showSlider(link_id, text, bLoadData, filter)
{
	var s	= $j('#linkcont-' + link_id).children().text();

	$j('#linkcont-' + link_id).children().unbind( "click" );
	$j('#linkcont-' + link_id).children()
		.bind( "click", function(event){
			hideSlider(link_id, s);
			return false;
	} )
		.html( text );

	if( true == bLoadData )
	{
		var oData	= null;

		$j('#linkcont-' + link_id).attr( 'class', 'votes_link_open' );
		$j('#slider-' + link_id).html('<div class="c"><img src="/templates/yuplay2/img/progress.gif"></div>');
		$j('#slider-' + link_id).css('display', 'block');

		$j.ajax({
			type: "GET",
			url: "/user.php?view=purch_data&id=" + link_id + "&type=" + filter + "&rand=" + Math.random(),
			success: function(data){ $j('#slider-' + link_id).html( data ) }
		});
	}
	else
	{
		$j('#linkcont-' + link_id).attr( 'class', 'votes_link_open' );
		$j('#slider-' + link_id).css('display', 'block');
	}
}

function showSlider2(link_id, text, bLoadData, filter)
{
	var s	= $j('#linkcont2-' + link_id).children().text();

	$j('#linkcont2-' + link_id).children().unbind( "click" );
	$j('#linkcont2-' + link_id).children()
		.bind( "click", function(event){
			hideSlider2(link_id, s);
			return false;
	} )
		.html( text );

	if( true == bLoadData )
	{
		var oData	= null;

		$j('#linkcont2-' + link_id).attr( 'class', 'votes_link_open' );
		$j('#slider2-' + link_id).html('<div class="c"><img src="/templates/yuplay2/img/progress.gif"></div>');
		$j('#slider2-' + link_id).css('display', 'block');

		$j.ajax({
			type: "GET",
			url: "/user.php?view=purch_data&id=" + link_id + "&type=" + filter + "&rand=" + Math.random(),
			success: function(data){ $j('#slider2-' + link_id).html( data ) }
		});
	}
	else
	{
		$j('#linkcont2-' + link_id).attr( 'class', 'votes_link_open' );
		$j('#slider2-' + link_id).css('display', 'block');
	}
}

function hideSlider(link_id, text)
{
	var s	= $j('#linkcont-' + link_id).children().text();

	$j('#linkcont-' + link_id).children().unbind( "click" );
	$j('#linkcont-' + link_id).children()
		.bind( "click", function(event) {
			showSlider( link_id, s, false);
			return false;
		} )
		.html( '<b>' + text + '</b>' );

	$j('#linkcont-' + link_id).attr( 'class', 'votes_link' );

	$j('#slider-' + link_id).css('display', 'none');
}

function hideSlider2(link_id, text)
{
	var s	= $j('#linkcont2-' + link_id).children().text();

	$j('#linkcont2-' + link_id).children().unbind( "click" );
	$j('#linkcont2-' + link_id).children()
		.bind( "click", function(event) {
			showSlider2( link_id, s, false);
			return false;
		} )
		.html( '<b>' + text + '</b>' );

	$j('#linkcont2-' + link_id).attr( 'class', 'votes_link' );

	$j('#slider2-' + link_id).css('display', 'none');
}

function set_cookie(name, value, expires)
{
  if (!expires)
  {
    expires = new Date();
  }
  document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}

function fbAInit(apiId)
{
   var expires = new Date();
   expires.setTime(expires.getTime()-1);
   set_cookie('return','',expires);
   
   window.fbAsyncInit = function() {
     FB.init({appId: apiId, status: true, cookie: true});
     FB.getLoginStatus(function(response) {
       if (response.session) {
         FB.logout();
       }
     });
   };
}

function fbLoginEvent(url, return_url, apiId)
{
  var expires = new Date();
  expires.setTime(expires.getTime() + (1000*60*3));
  set_cookie('return', return_url, expires);

  window.location.href = 'https://graph.facebook.com/oauth/authorize?client_id='
    +apiId+'&redirect_uri='+url+'&scope=email&display=page'
}

