/***********************************************
* Auto Height : http://lib.mobius.tw/jquery/myplugin/iframe_autoHeight/api.htm
***********************************************/

function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = e.contentDocument.body.offsetHeight + 35;
	} else {
		e.height = e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}

if (document.getElementById && document.createTextNode){
 addEvent(window,'load', doIframe);	
}

/***********************************************
* Detect Browser
***********************************************/
function detectBrowser() {
    var browser=navigator.appName;
    var b_version=navigator.appVersion;
    var version=parseFloat(b_version);
    
    var IE6=(navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) && (navigator.userAgent.toLowerCase().indexOf('msie 7') == -1);
    
    if(IE6)
    {
    	$('#announce2').show();
    }
}

/***********************************************
* Change CSS by david_kw http://www.exfer.net/blog/2008/01/26/a-cross-browser-changecss-function-to-alter-add-or-delete-css-rules/
***********************************************/
var exfer = window.exfer || {};
exfer.changeCSS = function (selector, stylename, value, valueType) {

  // Added by Khalil to solve the error problem
  	if (valueType == "hex") {
		if (value.length == 3) {
			value = value + value;
		} else if (value.length == 2) {
			value = value+value+value;
		} else if (value.length != 6) {
			value = "";
		}
	}

  var ss, rules;
  // make sure there is a stylesheet available
  if (document.styleSheets.length <= 0) {
    if (document.createStyleSheet) {
      document.createStyleSheet();
    } else {
      var styleTag = document.createElement("style");
      styleTag.type = "text/css";
      document.getElementsByTagName("head")[0].appendChild(styleTag);
    }
  }
  // convert the stylename to camel case if necessary
  ccstylename = (stylename || "").replace(/\-(\w)/g, function (m, c) { return (c.toUpperCase()); });
  ccstylename = (ccstylename == "float") ? "cssFloat" : ccstylename;
  selector = selector.toLowerCase();
  // loop to delete or change the css
  for (var i = 0; i < document.styleSheets.length; i++) {
    ss = document.styleSheets[i];
    try {
      rules = ss.cssRules || ss.rules;
    } catch (e) { 
      rules = []; 
    }
    for (var j = 0, len = rules.length; j < len; j++) {
      if (rules[j].selectorText) if (rules[j].selectorText.toLowerCase() == selector) { // problems in wordpress with 2 ampersands for and
        if (value != null) {
          rules[j].style[ccstylename] = value;
        } else {
          if (ss.deleteRule) {
            ss.deleteRule(j);
          } else if (ss.removeRule) {
            ss.removeRule(j);
          } else {
            // poor man\'s delete
            rules[j].style.cssText = "";
          }
        }
        return;
      }
    }
  }
  if (stylename) if (value) { // wordpress problems with 2 ampersands
    // if the selector wasn\'t found and isn\'t supposed to be deleted then add it
    ss = document.styleSheets[0];
    rules = ss.cssRules || ss.rules;
    if (ss.insertRule) {
      ss.insertRule(selector + "{" + stylename + ":" + value + "; }", rules.length);
    } else if (ss.addRule) {
      ss.addRule(selector, stylename + ":" + value + ";", rules.length);
    } else {
      throw new Error("Selector not found and add/insert rule not supported.");
    }
  }
};

/***********************************************
* Add Smileys http://polpoinodroidi.com/wordpress-plugins/smilies-themer-toolbar/
***********************************************/
function spaceSmiley(sm,pre) {
	// Add one ending space, always.
	sm = sm + ' ';

	var lastPreSmileyChar = pre.substr(pre.length - 1, 1);
	if (lastPreSmileyChar && lastPreSmileyChar != ' '
		&& lastPreSmileyChar.charCodeAt(0) != 10
		&& lastPreSmileyChar.charCodeAt(0) != 13) {
		sm = ' '+sm;
	}
	return sm;
}
function addSmiley(sm) {
				var area = document.getElementById('ctl00_cph1_txtComment');
				if (!area) return;
				var pre, pre, selStart,selEnd;
				area.focus();

				if (document.selection && !window.opera) {
					// I REALLY HATE Internet Explorer!!!!!
					var sel = document.selection.createRange();
					var sel2 = sel.duplicate();
					sel2.moveToElementText(area);
					sel2.setEndPoint('StartToEnd', sel);
					selEnd = area.value.length-sel2.text.length;
					sel2.setEndPoint('StartToStart', sel);
					selStart = area.value.length-sel.text.length;
					pre = area.value.substring(0,selStart);
					
					sm = spaceSmiley(sm,pre);
					sel.text = sm;
				}
				else {
					selStart = area.selectionStart;
					selEnd = area.selectionEnd;
					var testo = area.value;
					pre = testo.substring(0,selStart);
					post = testo.substring(selEnd);
					// if the character before the smiley is not a space, let's
					// add one before it. And add a space to the end.
					sm = spaceSmiley(sm, pre);
					
					var risultato = pre+sm+post;
					area.value = risultato;
				}
				
				area.selectionEnd = area.selectionStart = selStart + sm.length;
			}
			
/***********************************************
* Login Btn
***********************************************/
function dbtn(e, buttonid){
       var evt = e ? e : window.event;
       if (evt.keyCode == 13){
           var bt = document.getElementById(buttonid);
           if (bt){
               bt.click();
               return false;
           }
       }
   }
   
/***********************************************
* Remove Control (JQuery)
***********************************************/
function RemoveControl(control) { $(control).fadeOut(5000); }  

/***********************************************
* switchMenu (OLD)
***********************************************/
function switchMenu(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != "none" ) {
		el.style.display = 'none';
	}
	else if ( el.style.display == "" ) {
		el.style.display = 'none';
	}	
	else {
		el.style.display = '';
	}
}
function UpdatePost() {
    var el = document.getElementById('whatyoudoin');
    el.style.display = 'none';
}

function clearText(boxId)
{
    txtBox = document.getElementById(boxId);
    txtBox.value = "";
}

function Test()
{
    alert('Text');
}

function countstreamcomment(a, maxlimit){
    var dif = maxlimit-a.value.length;
    while(dif<0){
    a.value=a.value.replace(/.$/,'')
    dif = maxlimit-a.value.length;
    }
}

/* ARAKIAN */

var arakian = {
    /*logged_in: false,
    is_ie: !$.support.leadingWhitespace,
    load_settings: false,
    current_user: {
        place: {}
    },
    authenticity_token: "",*/
    init: function () {}
};

arakian.button = {
    init: function () {
    	$('#stream [href$="#comments"]').live("click", arakian.stream.comment.toggle);
    	$('#stream [href$="#commentinput"]').live("click", arakian.stream.comment.toggleinput);
    	$('#stream [class$="submitstatus"]').live("click", arakian.stream.comment.add2);
    	$('#stream [href$="#deleteStatus"]').live("click", arakian.stream.comment.delstatus);
    	$('#stream [href$="#deleteStatusComment"]').live("click", arakian.stream.comment.delstatuscomment);
    	
    	$('#stream [href$="#videocomments"]').live("click", arakian.stream.videocomment.toggle);
    	$('#stream [href$="#videocommentinput"]').live("click", arakian.stream.videocomment.toggleinput);
    	$('#stream [class$="submitvideocomment"]').live("click", arakian.stream.videocomment.add);    	
    	$('#stream [href$="#deleteVideo"]').live("click", arakian.stream.videocomment.delvideo);
    	$('#stream [href$="#deleteVideoComment"]').live("click", arakian.stream.videocomment.delvideocomment);

    }
};
arakian.stream = {
    path: "/objects.json",
    last_path: "/objects.json",
    live: false,
    last: 0,
    first: 0,
    loading: 0,
    init: function () {}
};
arakian.stream.comment = {
    object: null,
    element: null,
    toggle: function () {
        var a = $(this).closest(".body2").find(".toggle");
        a.toggle();
        if (a.is(":visible")) {
            a.find("textarea").focus()
        }
        return false
    },
    toggleinput: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        a.toggle();
        if (a.is(":visible")) {
            a.find("textarea").focus()
        }
        return false
    },
    delstatus: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        
        $.blockUI({ message: $('#modalpopup') });
        
        var b = $(this).attr('name');
        
        var c = $(this).closest(".text");
        
        $('.dialog_summary').html("Delete Post");
        
        $('.modalContent').html("Are you sure you want to delete this post ?");
        
	$(".dialog_buttons").append("<input id='modalpopup-yes-" + b + "' type='button' class='inputsubmit' name='modalConfirm' value='Confirm' /> <input id='modalpopup-close-" + b + "' type='button' class='inputsubmit' name='modalCancel' value='Cancel' />");

        //$('#modalpopup-yes').attr('class',b);
        //$('#modalpopup-yes').attr('title','Click to close');

        $("#modalpopup-yes-" + b).attr('title','Click to confirm').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ 
                 	$(".dialog_buttons").html("");

			$.ajax({
			    type: "post",
			    url: "api/status/statuscomment.aspx/DeletePost",
			    data: '{"id":"'+encodeURIComponent(b)+'"}',
			    contentType: "application/json; charset=utf-8",
			    dataType: "json",            
			    success: function (f) {
				c.html('');
			    },
			    error: function (e) {
				alert("There was an error while deleting your post. Please try again.");
			    },
			    complete: function () {
				//c.removeClass("loading")
			    }
			});
                 } 
            });
        });
        
        $("#modalpopup-close-" + b).attr('title','Click to close').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ $(".dialog_buttons").html(""); } 
            });
        });
        
        return false
    },
    delstatuscomment: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        
        $.blockUI({ message: $('#modalpopup') });
        
        var b = $(this).attr('name');
        
        var c = $(this).closest(".miniCommentParent").find("#miniblog-comment-"+b);
        
        var d = $(this).closest(".miniCommentParent").find("#miniblog-comment-"+b).attr('name');

        $('.dialog_summary').html("Delete Comment");
        
        $('.modalContent').html("Are you sure you want to delete this comment ?");
        
	$(".dialog_buttons").append("<input id='modalpopup-yes-" + b + "' type='button' class='inputsubmit' name='modalConfirm' value='Confirm' /> <input id='modalpopup-close-" + b + "' type='button' class='inputsubmit' name='modalCancel' value='Cancel' />");

        $("#modalpopup-yes-" + b).attr('title','Click to confirm').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ 
                 	$(".dialog_buttons").html("");

			$.ajax({
			    type: "post",
			    url: "api/status/statuscomment.aspx/DeletePostComment",
			    data: '{"id":"'+encodeURIComponent(b)+'", "oid":"'+encodeURIComponent(d)+'"}',
			    contentType: "application/json; charset=utf-8",
			    dataType: "json",            
			    success: function (f) {
				c.remove();
			    },
			    error: function (e) {
				alert("There was an error while deleting your comment. Please try again.");
			    },
			    complete: function () {
				//c.removeClass("loading")
			    }
			});			
                 } 
            });
        });
        
        $("#modalpopup-close-" + b).attr('title','Click to close').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ $(".dialog_buttons").html(""); } 
            });
        });
        
        return false
    },    
    add2: function () {
        var a = $(this).closest(".postcommentbody").find("input[type='hidden']");
        var b = $(this).closest(".postcommentbody").find("textarea[class$='streamcomment']");
        
        var h = $(this);
        h.attr('disabled', 'disabled');
        b.attr('readonly', 'readonly');
        
        var i = h.closest(".btnButton");      
        i.html('<img src="images/ajax-loader2.gif" class="loading" />');
        
        $.ajax({
            type: "post",
            url: "api/status/statuscomment.aspx/Submit",
            data: '{"id":"'+encodeURIComponent(a.val())+'", "msg":"'+encodeURIComponent(b.val())+'"}',
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",            
            success: function (f) {
                b.val("");
                var c = b.closest(".body2");
                var j = c.children(".miniCommentParent");
                j.append(f);
                var d = c.find(".postcomment");
                
		h.attr('disabled', '');
		b.attr('readonly', '');                
                
                d.hide();
                
                i.html('<input type="button" class="submitstatus" name="streamCommentSubmit" value="Comment" id="streamCommentSubmit" />');
            },
            error: function (e) {
                alert("There was an error posting your comment. Please try again.");
                i.html('<input type="button" class="submitstatus" name="streamCommentSubmit" value="Comment" id="streamCommentSubmit" />');
            },
            complete: function () {
                //c.removeClass("loading")
            }
        });       
        
        return false
    },    
    add: function () {
        var a = $(this).closest(".postcommentbody").find("input[type='hidden']");
        var b = $(this).closest(".postcommentbody").find("textarea[class$='streamcomment']");
        //alert(a.attr("value"));
        //alert(b.attr("value"));
        
        $.ajax({
            type: "post",
            url: "api/status/statuscomment.aspx/Submit",
            data: '{"id":"'+encodeURIComponent(a.val())+'", "msg":"'+encodeURIComponent(b.val())+'"}',
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",            
            success: function (f) {
                b.val("");
                var c = b.closest(".body2");
                var j = c.children(".miniCommentParent");
                j.append(f);
                var d = c.find(".postcomment");
                d.hide();

                //j.html(f).show();
                //var f = new Array(f);
                //    h = c.closest(".comments"),
                //    j = h.children(".wrapper"),
                //    e = "",
                //    g = parseInt(b.find(".comments").attr("rel")) + 1;
                //if (g == 1) {
                //    j.html(arakian.stream.comment.generate(f)).show()
                //} else {
                //    j.append(arakian.stream.comment.generate(f))
                //}
                //b.find(".comments").attr("rel", g);
                //b.find('[href$="#comments"]').text("comment (" + g + ")");
                //h.children("div").show();
                //if (d) {
                //    arakian.stream.comment.condense(b)
                //}
                //alert(f);
            },
            error: function (e) {
                alert("There was an error posting your comment. Please try again.")
            },
            complete: function () {
                //c.removeClass("loading")
            }
        });       
        
        return false
    }
};
arakian.stream.videocomment = {
    object: null,
    element: null,
    toggle: function () {
        var a = $(this).closest(".body2").find(".toggle");
        a.toggle();
        if (a.is(":visible")) {
            a.find("textarea").focus()
        }
        return false
    },
    toggleinput: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        a.toggle();
        if (a.is(":visible")) {
            a.find("textarea").focus()
        }
        return false
    },
    delvideo: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        
        $.blockUI({ message: $('#modalpopup') });
        
        var b = $(this).attr('name');
        
        var c = $(this).closest(".text");
        
        $('.dialog_summary').html("Delete Post");
        
        $('.modalContent').html("Are you sure you want to delete this post ?");
        
	$(".dialog_buttons").append("<input id='modalpopup-yes-" + b + "' type='button' class='inputsubmit' name='modalConfirm' value='Confirm' /> <input id='modalpopup-close-" + b + "' type='button' class='inputsubmit' name='modalCancel' value='Cancel' />");

        $("#modalpopup-yes-" + b).attr('title','Click to confirm').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ 
                 	$(".dialog_buttons").html("");

			$.ajax({
			    type: "post",
			    url: "api/videos/videocomment.aspx/DeletePost",
			    data: '{"id":"'+encodeURIComponent(b)+'"}',
			    contentType: "application/json; charset=utf-8",
			    dataType: "json",            
			    success: function (f) {
				c.html('');
			    },
			    error: function (e) {
				alert("There was an error while deleting your post. Please try again.");
			    },
			    complete: function () {
				//c.removeClass("loading")
			    }
			});
                 } 
            });
        });
        
        $("#modalpopup-close-" + b).attr('title','Click to close').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ $(".dialog_buttons").html(""); } 
            });
        });
        
        return false
    },
    delvideocomment: function () {
        var a = $(this).closest(".body2").find(".postcomment");
        
        $.blockUI({ message: $('#modalpopup') });
        
        var b = $(this).attr('name');
        
        var c = $(this).closest(".miniCommentParent").find("#video-comment-"+b);
        
        var d = $(this).closest(".miniCommentParent").find("#video-comment-"+b).attr('name');

        $('.dialog_summary').html("Delete Comment");
        
        $('.modalContent').html("Are you sure you want to delete this comment ?");
        
	$(".dialog_buttons").append("<input id='modalpopup-yes-" + b + "' type='button' class='inputsubmit' name='modalConfirm' value='Confirm' /> <input id='modalpopup-close-" + b + "' type='button' class='inputsubmit' name='modalCancel' value='Cancel' />");

        $("#modalpopup-yes-" + b).attr('title','Click to confirm').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ 
                 	$(".dialog_buttons").html("");

			$.ajax({
			    type: "post",
			    url: "api/videos/videocomment.aspx/DeletePostComment",
			    data: '{"id":"'+encodeURIComponent(b)+'", "oid":"'+encodeURIComponent(d)+'"}',
			    contentType: "application/json; charset=utf-8",
			    dataType: "json",            
			    success: function (f) {
				c.remove();
			    },
			    error: function (e) {
				alert("There was an error while deleting your comment. Please try again.");
			    },
			    complete: function () {
				//c.removeClass("loading")
			    }
			});			
                 } 
            });
        });
        
        $("#modalpopup-close-" + b).attr('title','Click to close').click(function () {
	    $.unblockUI({ 
                 onUnblock: function(){ $(".dialog_buttons").html(""); } 
            });
        });
        
        return false
    },    
    add: function () {
        var a = $(this).closest(".postcommentbody").find("input[type='hidden']");
        var b = $(this).closest(".postcommentbody").find("textarea[class$='streamcomment']");
        
        var h = $(this);
        h.attr('disabled', 'disabled');
        b.attr('readonly', 'readonly');
        
        var i = h.closest(".btnButton");      
        i.html('<img src="images/ajax-loader2.gif" class="loading" />');
        
        $.ajax({
            type: "post",
            url: "api/videos/videocomment.aspx/Submit",
            data: '{"id":"'+encodeURIComponent(a.val())+'", "msg":"'+encodeURIComponent(b.val())+'"}',
	    contentType: "application/json; charset=utf-8",
	    dataType: "json",            
            success: function (f) {
                b.val("");
                var c = b.closest(".body2");
                var j = c.children(".miniCommentParent");
                j.append(f);
                var d = c.find(".postcomment");
                
		h.attr('disabled', '');
		b.attr('readonly', '');                
                
                d.hide();
                
                i.html('<input type="button" class="submitvideocomment" name="streamCommentSubmit" value="Comment" id="streamCommentSubmit" />');
            },
            error: function (e) {
                alert("There was an error posting your comment. Please try again.");
                i.html('<input type="button" class="submitvideocomment" name="streamCommentSubmit" value="Comment" id="streamCommentSubmit" />');
            },
            complete: function () {
                //c.removeClass("loading")
            }
        });       
        
        return false
    }
};    
$(function () {
	
});