﻿
// ----------
// sniff for IE

is_ie = 0;
(function(){
  /* MSIE sniffing */
  /*@cc_on
    is_ie = {
      version : parseFloat(navigator.appVersion.match(/MSIE ([^;]+)/)[1]),
      quirksmode : (document.compatMode=="BackCompat")
    };
  @*/;
})(); 


// ----------
// this exposes things dependent on javascript

/*(function(){
  document.body.className += " jspresent";
})(); 
*/

// ----------
// this makes sure, when column1 is 
// absolute positioned, that the body
// height is the same
/*
(function(){

  var elmH = function (eId) { 
    var _elm = document.getElementById(eId);
    return (_elm && _elm.offsetHeight) || 0; 
  }

  var lastX = 0;
  var styleProp = (is_ie && (is_ie.version < 7 || is_ie.quirksmode)) ? "height" : "minHeight";

  function fixHeight() {
    
    var _mh  = elmH("pagebody");
    var _xh  = elmH("pageextra1");
    var _pb  = document.getElementById("pagebody");

    // changed?
    if (lastX != _xh || _xh > _mh) {
      _pb.style[styleProp] = _xh + "px";
    }

    lastX = _xh;
    
  };

  (window.onresize = fixHeight)(); // set and run
  setInterval(fixHeight, 1000);  // check for font resize every second

})();
*/

function SelectMessage(messageId)
{
    //alert("WTF!!");
    var message = $("div[@id="+messageId+"]");

    if (message.attr("class").indexOf("current")>-1)
    {
        message.removeClass("current");
        return;
    }

    $("div[@id:contains('message')]").each(function(i) {
        if (this.className.indexOf("current")>-1)
            $("div[@id="+this.id+"]").removeClass("current");
        }
    );
    
    $("div[@id:contains('reply')]").each(function(i) {
        if (this.className.indexOf("current")>-1)
            $("div[@id="+this.id+"]").removeClass("current");
        }
    );
    
    if (message.attr("class").indexOf("unread")>-1)
    {
        message.removeClass("unread");

        $.ajax({
            type: "POST",
            url: "Ajax/Message.ashx",
            data: "messageid="+messageId.replace(/message/,""),
            success: function(msg){
                //alert( "Data Saved: " + msg );
            }
        });
    }
    
    message.addClass("current");
    
  
    //alert(messageId.replace(/message/,""));
}

function ShowReply(messageId)
{
    var message = $("div[@id="+messageId+"]");
    if (message.attr("class").indexOf("current")>-1)
    {
        message.removeClass("current");
        return;
    }
    
    $("div[@id:contains('reply')]").each(function(i) {
            if (this.className.indexOf("current")>-1)
            {
                if (this.id.indexOf("reply")>-1)
                {
                    $("div[@id="+this.id+"]").removeClass("current");
                }
            }
        });
    
    //alert(message.id);
    
    message.addClass("current");
}

function CheckAllToggle(chkBox)
{
    $("input[@type=checkbox]").each(function(i) {
        this.checked = chkBox.checked;
    });
}

function CountText()
{
    
    var smsMessage = $("textarea[@class=smsText]")
    var smsMaxChars = $("input[@class=smsMaxChars]")
        
    var smsMessageCountSpan = $("span[@id=smsMessageLength]")
    var smsTotalMessagesSpan = $("span[@id=smsTotalMessages]")

    smsMessageCountSpan.empty();
    smsMessageCountSpan.append(smsMessage.val().length);

    smsTotalMessagesSpan.empty();
    smsTotalMessagesSpan.append(Math.ceil(smsMessage.val().length / smsMaxChars.val()) );
}

function CheckBoxCheck(source, args) 
{
    $("input[@type=checkbox][@id:contains(cbxConditions)]").each(function(i) {
        if ($(this).attr("id").indexOf("cbxConditions")>-1)
		    args.IsValid = $(this).is(":checked"); 
	});
}

function VerifyTextAreaContent(source, args)
{
    if (tinyMCE.getContent().length>0)
        args.IsValid = true
    else
        args.IsValid = false
        
}

/*function CheckBoxVerification()
{
    if (tinyMCE!=null)
    {
        alert("test 1");
        $("input[@type=checkbox][@id:contains(chkSendSMS)]").each(function(i) {
            alert("test 2");
            if ($(this).attr("id").indexOf("cbxConditions")>-1)
                {
                    alert("test 3");
                    $(this).is(":checked") = false; 
		        //args.IsValid = $(this).is(":checked"); 
		        }
	    });
	}
        
}*/

/*$(document).ready(function() {
   CheckBoxVerification()
   });*/

/*
 *  KeepSessionAlive
 *  Make an ajax callback to a blank page to keep the session alive.
 *
 */
function KeepSessionAlive()
{
    // Interval between callbacks in minutse
    //var minutes = 10;

    // The ajax callback
    //$.ajax({
    //    type:           "GET",
    //    url:            "/blank.aspx",
    //});
    
    // Set the timeout
    //setTimeout(KeepSessionAlive, ((minutes * 60) * 1000));
}

function CheckForPendingChat()
{

    var timestamp=new Date();
    var tmpString = "" + timestamp.getDate();
    tmpString = tmpString + "" + timestamp.getHours();
    tmpString = tmpString + "" + timestamp.getMinutes();
    tmpString = tmpString + "" + timestamp.getSeconds();
    $.get("/Ajax/InstantMessenger.ashx?function=UserInfoList&" + tmpString, function(data){
        if (data.length>0)
        {
            setTimeout(CheckForPendingChat, (40 * 1000));
            var userInfoIDArray = data.split(";")
            for (i=1;i< data.length;i++)
            {
                if (userInfoIDArray[i].length>0)
                {
                    var userInfoArray = userInfoIDArray[i].split(":")
                    if(confirm("Viltu spjalla við " + userInfoArray[0] + "?"))
                    {
                        launchWM( userInfoIDArray[0], userInfoArray[1] );
                    }
                    else
                    {
                        if (confirm("Viltu setja " + userInfoArray[0] + " á bannlistann þinn?"))
                            $.get("/Ajax/InstantMessenger.ashx?function=Ban&userInfoID=" + userInfoArray[1] + "&tmp=" + tmpString);
                        else
                            $.get("/Ajax/InstantMessenger.ashx?function=TimeOut&userInfoID=" + userInfoArray[1] + "&tmp=" + tmpString);
                    }
                }
            }
        }
        else
        {
            //setTimeout(CheckForPendingChat, (20 * 1000));
        }
    }
    )
    
    
}

		function launchWM( userID, destinationUserID )
		{
			var popupWindowTest = window.open( "/WMPopUp.aspx?strDestinationUserID=" + destinationUserID, "WMWindow_" + userID + "_" + destinationUserID, "width=500,height=600,toolbar=0,directories=0,menubar=0,status=0,location=0,scrollbars=0,resizable=0" );
			if( popupWindowTest == null )
			{
				alert( "Gluggaverjan þín gerði það að verkum að ekki var hægt að opna nýjan glugga!" );
			}
		}

		function replaceAlpha( strIn )
		{
			var strOut = "";
			for( var i = 0 ; i < strIn.length ; i++ )
			{
				var cChar = strIn.charAt(i);
				if( ( cChar >= 'A' && cChar <= 'Z' )
					|| ( cChar >= 'a' && cChar <= 'z' )
					|| ( cChar >= '0' && cChar <= '9' ) )
				{
					strOut += cChar;
				}
				else
				{
					strOut += "_";
				}
			}

			return strOut;
		}
		
function DisableControl(controlId) {
	document.getElementById(controlId).disabled = true;
}

function DisableControl_SetTimeout(controlId, interval) {
	setTimeout("DisableControl('" + controlId + "')", interval);
}

function btn_ClickDisableWithValidation(control) {
    Page_ClientValidate();
    if (Page_IsValid)
	    DisableControl_SetTimeout(control.id, 100);
}

function Message(messageid,read,date,sendername,senderid,title,summary,message,gender,friendly,isSibling)
{
    this.MessageID = messageid;
    this.Read = read;
    this.Date = date;
    this.Sender = sendername;
    this.SenderID = senderid;
    this.Title = title;
    this.Summary = summary;
    this.Message = message;
    this.Gender = gender;
    this.Friendly = friendly;
    this.HasParents = HasParentsClass(isSibling);
    
    return this;
}

function UnreadClass(value)
{
    if (!value)
        return "unread";
    else
        return "";
}

function HasParentsClass(value)
{
    if (!value)
        return "hideme";
    else
        return "";
}

jQuery.create = function() {
if (arguments.length == 0) return [];
var args = arguments[0] || {}, elem = null, elements = null;
var siblings = null;

// In case someone passes in a null object,
// assume that they want an empty string.
if (args == null) args = "";
if (args.constructor == String) {
    if (arguments.length > 1) {
        var attributes = arguments[1];
            if (attributes.constructor == String) {
                        elem = document.createTextNode(args);
                        elements = [];
                        elements.push(elem);
                        siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
                        elements = elements.concat(siblings);
                        return elements;

                } else {
                        elem = document.createElement(args);

                        // Set element attributes.
                        var attributes = arguments[1];
                        for (var attr in attributes)
                            jQuery(elem).attr(attr, attributes[attr]);

                        // Add children of this element.
                        var children = arguments[2];
                        children = jQuery.create.apply(null, children);
                        jQuery(elem).append(children);

                        // If there are more siblings, render those too.
                        if (arguments.length > 3) {
                                siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
                                return [elem].concat(siblings);
                        }
                        return elem;
                }
        } else return document.createTextNode(args);
  } else {
          elements = [];
          elements.push(args);
          siblings = jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
          elements = elements.concat(siblings);
          return elements;
  }
};

function MakeHome() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage('http://www.einkamal.is');

    }
    else if (window.sidebar) {
        if (window.netscape) {
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', 'http://www.einkamal.is');
        }
    }
}

function CreateNewPopupSpecific(url, width, height) {
    newwindow = window.open(url, 'Other', 'height=' + height + ',width=' + width + ',alwaysRaised=1,dependant=1');
    if (!newwindow.opener) newwindow.opener = self;
}

function CreateNewPopupSpecificWithScrollbar(url, width, height) {
    newwindow = window.open(url, 'Other', 'height=' + height + ',width=' + width + ',alwaysRaised=1,dependant=1,scrollbars=1');
    if (!newwindow.opener) newwindow.opener = self;
}