// Utility Functions
if (typeof $ == 'undefined') {
    $ = function(id) {
    	if (typeof id == 'string') {
    		return document.getElementById(id);
    	}
    	return id;
    }
}

var Util = {
    popup: function(url, width, height) {
        window.open('http://csr.rhofam.com/popups/' + url, '','width=' + width + 'px, height=' + height + 'px, resizable, scrollbars');
    }
};

function getScrollPos() {
	if (window.pageYOffset) {
		return { x: window.pageXOffset, y: window.pageYOffset };
	}
	else if (document.body.scrollTop) {
		return { x: document.body.scrollLeft, y: document.body.scrollTop };
	}
	else if (document.documentElement && document.documentElement.scrollTop) {
		return { x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop };
	}
	return { x: 0, y: 0 };
};


window.getSize = function() {
	var w = 0, h = 0;
	
	if (typeof (window.innerWidth) == 'number' ) {
		//Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	}
	else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	}
	return { w: w, h: h }
};


function $create(type, fallbackParent) {
	if (type instanceof Array) {
		var array = type;
		var parts = array[0].split('.');
		var el = $create(parts[0]);
		if (parts[1]) el.className = parts[1];
		
		var childrenStart;
		if (array.length >= 2) {
			var name;
			if (typeof array[1] == 'object' && !(array[1] instanceof Array)) {
				var attribs = array[1];
				for (var i in attribs) {
					switch (i) {
						case 'style': 
							el.style.cssText = attribs[i];
							el.setAttribute('style', attribs[i]);
						break;
						default: el[i] = attribs[i];
					}
					
				}
				childrenStart = 2;
			}
			else {
				childrenStart = 1;
			}
			
			for (var i = childrenStart, len = array.length; i < len; ++ i) {
				var child = array[i];
				if (typeof child == 'string') {
					el.appendChild(document.createTextNode(child));
				}
				else {
					var childEl, parentEl;
					if (typeof fallbackParent == 'undefined' || typeof el.$ != 'undefined') {
						parentEl = el;
					}
					else {
						parentEl = fallbackParent;
					}
					
					childEl = $create(child, parentEl);
					
					if (typeof childEl.$ != 'undefined') {
						parentEl[childEl.$] = childEl;
					}
					el.appendChild(childEl);
				}
			}
		}
		return el;
	}
	return document.createElement(type);
}

function $screenPos(el) {
	var p = { x: 0, y: 0 };
	var e = el;
	while (el) {
		p.x += el.offsetLeft;
		p.y += el.offsetTop;
		el = el.offsetParent;
	}
	el = e.parentNode;
	while (el) {
		if (el.scrollLeft) {
			p.x -= el.scrollLeft;
		}
		if (el.scrollTop) {
			p.y -= el.scrollTop;
		}
		el = el.parentNode;
	}
	
	return p;
}

function $pos(el) {
	var p = { x: 0, y: 0 };
	while (el) {
		p.x += el.offsetLeft;
		p.y += el.offsetTop;
		el = el.offsetParent;
	}
	
	return p;
}


var Something = {
    isIE6: false /*@cc_on || @_jscript_version < 5.7 @*/,
    isIE: /*@cc_on!@*/false, 
    
    setCaretPos: function(field, start, end) {
        // IE
        if (Something.isIE) { 
            // Set focus on the element
            field.focus();

            // Create empty selection range
            var sel = document.selection.createRange();

            // Move selection start and end to 0 position
            sel.moveStart ('character', -field.value.length);

            // Move selection start and end to desired position
            sel.moveStart('character', start);
            sel.moveEnd('character', start + end);
            sel.select();
        }

        // Normal browsers
        else {
            field.selectionStart = start;
            field.selectionEnd = end;
        }
    },
    getCaretPos: function(field) {
        // IE
        if (Something.isIE) { 
            // Set focus on the element
            field.focus();

            // To get cursor position, get empty selection range
            var sel = document.selection.createRange();

            // Move selection start to 0 position
            sel.moveStart('character', -field.value.length);

            // The caret position is selection length
            var pos = sel.text.length;
            
            return { start: pos, end: pos };
        }

        // Normal browsers
        return { start: field.selectionStart, end: field.selectionEnd };
    }
};

function PopupFrame(cont, dontShowCloseLink) {
  /*var frame = $create(['div', {style:'display:none; position:absolute; background-color:#fff; padding:10px; z-index:1000'}, 
    ['span', {$:'closeLink', style:'cursor:pointer;color:#B0292F;font-weight:bold;font-size:12px;font-family:serif;', href:'#'}, 'CLOSE'] 
  ]); */


  var frame = $create(
    ['div.frame',
    ['div.f00',
    ['div.f01',
    ['div.f1',
    ['div.f2',
    ['div.f3',
    ['div.f4',
    ['div.f5',
    ['div.f6',
    ['div.f7',
    ['div.f8',
    ['div.client', {$:'client'}, ['span.close', {$:'closeLink'}]]]]]]]]]]]]]
  );
  
  frame.client.appendChild(cont);

  var close = document.createElement('span');
  close.innerHTML = 'click outside to close';
  close.style.position = 'absolute';
  close.style.right = '10px';
  close.style.bottom = '-18px';
  close.style.color = 'white';
  close.style.fontWeight = 'bold';
  frame.client.appendChild(close);


  frame.closeLink = frame.client.closeLink;

  var isIE6 = Something.isIE6;

  //if (dontShowCloseLink) frame.closeLink.style.display = 'none';

  return frame;
}

// I made a function to create popups! Isn't it neat? 
function createPopup(el, dontShowCloseLink) { 
  var scrollPos = getScrollPos();
  var overlay = $create(['div', {style:'display:none;position:absolute; width:100%; height:100%; left:' + scrollPos.x + 'px; top:' + scrollPos.y + 'px; z-index:999; background-color:black'}]);

  var cont = $create(['div', {style:'display:none; position:absolute; background-color:#fff; padding:10px; z-index:1000'}, 
    ['span', {$:'closeLink', style:'cursor:pointer;color:#B0292F;font-weight:bold;font-size:12px;font-family:serif;', href:'#'}, 'CLOSE'] 
  ]); 
  
  cont.insertBefore(el, cont.closeLink);

  var isIE6 = Something.isIE6;

  if (isIE6) { 
    var windowSize = window.getSize();
    overlay.style.width = windowSize.w + 'px';
    overlay.style.height = windowSize.h + 'px'; 
  }

  if (dontShowCloseLink) cont.closeLink.style.display = 'none';

  cont.closeLink.onclick = function() {
    close();
    return false;
  }

  overlay.onclick = function() {
    close();
  }
  jQuery(overlay).css('opacity', 0.3);

  function close() {
    jQuery(overlay).fadeOut(function() {
      document.body.removeChild(overlay);
    });
    jQuery(cont).fadeOut(function() {
      document.body.removeChild(cont);
    });
  }

  document.body.appendChild(overlay);
  document.body.appendChild(cont);

  return {
    show: function() {
      var windowSize = window.getSize();
      jQuery(overlay).fadeIn();
      //if (isIE6) overlay.style.backgroundColor = 'white';
      cont.style.visibility = 'hidden';
      cont.style.display = 'block';
      cont.style.left = scrollPos.x + (windowSize.w/2 - cont.offsetWidth/2) + 'px';
      cont.style.top = scrollPos.y + (windowSize.h/2 - cont.offsetHeight/2) + 'px';
      cont.style.display = 'none';
      cont.style.visibility = 'visible';
      jQuery(cont).fadeIn();
    },
    close: function() {
      close();
    }
  };
}

function createImageView(src) {
    var el = $create(['img', {$:'img', style:'margin-bottom:5px;display:block'}]);

        var popup = createPopup(el);
         el.onload = function() {
                popup.show();
        }
        el.src = src;
}

var Popup = {
  _overlay: null,
  _currentPopup: null,

  // Overlay
  showOverlay: function() {
    if (!this._overlay) {
      var scrollPos = getScrollPos();
      var overlay = $create(['div', {style:'display:none;position:fixed; width:100%; height:100%; left:' + scrollPos.x*0 + 'px; top:' + scrollPos.y*0 + 'px; z-index:999; background-color:black'}]);
      jQuery(overlay).css('opacity', 0.3);
      var isIE6 = Something.isIE6;
      if (isIE6) { 
        var windowSize = window.getSize();
        overlay.style.width = windowSize.w + 'px';
        overlay.style.height = windowSize.h + 'px'; 
      }

      overlay.onclick = function() {
        Popup.close(); 
      }
      document.body.appendChild(overlay);
      jQuery(overlay).fadeIn();

      this._overlay = overlay;
    }
  },


  hideOverlay: function() {
    if (this._overlay) {
      var overlay = this._overlay;
      this._overlay = null;
      jQuery(overlay).fadeOut(function() {
        overlay.parentNode.removeChild(overlay);
      });
    }
  },

  // Create popup
  create: function(cont) {
    if (cont.closeLink) {
      cont.closeLink.onclick = function() {
        Popup.close();
        return false;
      }
    }

    function close(cb) {
      jQuery(cont).fadeOut(function() {
        document.body.removeChild(cont);
        if (cb) cb(); 
      });
    }

    return {
      show: function() {
        document.body.appendChild(cont);
        var scrollPos = getScrollPos();
        var windowSize = window.getSize();
        cont.style.position = 'fixed';
        cont.style.zIndex = 1000;
        cont.style.visibility = 'hidden';
        cont.style.display = 'block';
        // It seems like in IE7 it takes some time before the element resets its layout after you change its display type.
        // So we need to wait a bit before we access offsetWidth
        setTimeout(function() {
          cont.style.left = (windowSize.w/2 - cont.offsetWidth/2) + 'px';
          cont.style.top = (windowSize.h/2 - cont.offsetHeight/2) + 'px';
          cont.style.display = 'none';
          cont.style.visibility = 'visible';
          jQuery(cont).fadeIn();
        }, 1);
      },
      close: function(cb) {
        close(cb);
      }
    };
  },

  close: function(cb) {
    this.hideOverlay();
    if (this._currentPopup) {
      this._currentPopup.close(function() {
        jQuery(document.body).removeClass('hide-flash');
      });
      this._currentPopup = null;
    }  
  },

  open: function(cont) {
    var that = this;
    if (this._currentPopup) {
      this._currentPopup.close(nextStep);
    } 
    else {
      this.showOverlay();
      nextStep();
    }

    function nextStep() {
      var popup = that.create(cont);
      that._currentPopup = popup;
      popup.show();
    }

    jQuery(document.body).addClass('hide-flash');
  }
};

// I made a function to create popups! Isn't it neat? 
function createCustomPopup(cont) { 
  var scrollPos = getScrollPos();
  var overlay = $create(['div', {style:'display:none;position:absolute; width:100%; height:100%; left:' + scrollPos.x + 'px; top:' + scrollPos.y + 'px; z-index:999; background-color:black'}]);

  var isIE6 = Something.isIE6;

  if (isIE6) { 
    var windowSize = window.getSize();
    overlay.style.width = windowSize.w + 'px';
    overlay.style.height = windowSize.h + 'px'; 
  }

  if (cont.closeLink) {
    cont.closeLink.onclick = function() {
      close();
      return false;
    }
  }

  overlay.onclick = function() {
    close();
  }
  jQuery(overlay).css('opacity', 0.3);

  function close() {
    jQuery(overlay).fadeOut(function() {
      document.body.removeChild(overlay);
    });
    jQuery(cont).fadeOut(function() {
      document.body.removeChild(cont);
    });
  }

  document.body.appendChild(overlay);
  document.body.appendChild(cont);

  return {
    show: function() {
      var windowSize = window.getSize();
      jQuery(overlay).fadeIn();
      //if (isIE6) overlay.style.backgroundColor = 'white';
      cont.style.position = 'absolute';
      cont.style.zIndex = 1000;
      cont.style.visibility = 'hidden';
      cont.style.display = 'block';
      cont.style.left = scrollPos.x + (windowSize.w/2 - cont.offsetWidth/2) + 'px';
      cont.style.top = scrollPos.y + (windowSize.h/2 - cont.offsetHeight/2) + 'px';
      cont.style.display = 'none';
      cont.style.visibility = 'visible';
      jQuery(cont).fadeIn();
    },
    close: function() {
      close();
    }
  };
}


// Model Functions
var Content = {
  rate: function(id) {
    if (!User.loggedIn) {
      User.showLoginForm();
      return;
    }
    new Ajax.Request('/votes/create.json', {
      method: 'post',
      parameters: {
        'authenticity_token': formAuthenticityToken,
        'vote[content_id]': id
      },
      onSuccess: function() {
        $(id + '.rating').innerHTML = parseInt($(id + '.rating').innerHTML) + 1;
        $(id + '.i-like-this').innerHTML = 'Liked';
      }
    });
  },
  flag: function(id, link) {
    if (!User.loggedIn) {
      User.showLoginForm();
      return;
    }
    var el = $create(
      ['div', {id:'flag-form'}, 
        ['h1', {style:'background-image: url(/images/contents/flag/header.png)'}, 'Flag content'],
        ['p', 'Please write a brief comment to the auther of this content.'],
        ['label', 'Comment:'], ['textarea', {$:'comment'}],
        ['p', {style:'clear:both'}, 
          ['label', {'for':'share_email', style:'width:auto'}, 'Share your email:'], ['input', {$:'share_email', type:'checkbox', name:'share_email', id:'share_email'}]
        ],
        ['span.options', ['input', {$:'submit', type:'submit', value:'Submit'}], ' | ', ['a.cancel', {$:'cancel', href:'#'}, 'Cancel']]
      ]
    );
    el.cancel.onclick = function() {
      Popup.close();
      return false;
    }

    el.submit.onclick = function() {
      el.comment.disabled = true;
      el.submit.disabled = true;
      el.submit.value = 'Sending...';
      new Ajax.Request('/flags/create.json', {
        method: 'post',
        parameters: {
          'authenticity_token': formAuthenticityToken,
          'flag[content_id]': id,
          'flag[comment]': el.comment.value,
          'flag[share_email]': el.share_email.checked
        },
        onSuccess: function() {
          Popup.close();
          link.innerHTML = 'Flagged';
        }
      });
      return false;
    }

    Popup.open(PopupFrame(el, true));
  }
}

var User = {
  ensureLoggedIn: function(url) {
    if (!this.loggedIn) {
      User.showLoginForm(url); 
      return false;
    }
    return true;
  }
};
