/*------------JSON JS---------------- */
Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}
var Hash = function(object) {
  if (object instanceof Hash) this.merge(object);
  else Object.extend(this, object || {});
};

Object.extend(Object,{
  toJSON: function(object) {
    var type = typeof object;
    //alert(type+" => "+object);
    switch(type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }
    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (object.ownerDocument === document) return;
    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ':' + value);
    }
    return '{' + results.join(',') + '}';
  }
});
Object.extend(Number.prototype,{
  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});
Object.extend(Date.prototype,{
  toJSON: function() {
    return '"' + this.getFullYear() + '-' +
    (this.getMonth() + 1).toPaddedString(2) + '-' +
    this.getDate().toPaddedString(2) + 'T' +
    this.getHours().toPaddedString(2) + ':' +
    this.getMinutes().toPaddedString(2) + ':' +
    this.getSeconds().toPaddedString(2) + '"';
  }
});
Object.extend(String.prototype,{
  toJSON: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    return '"' + escapedString.replace(/"/g, '\\"') + '"';
  }
});
Object.extend(Array.prototype,{
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },
  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (value !== undefined) results.push(value);
    });
    return '[' + results.join(',') + ']';
  }
});
Object.extend(Hash, {
  toJSON: function(object) {
    var results = [];
    this.prototype._each.call(object, function(pair) {
      var value = Object.toJSON(pair.value);
      if (value !== undefined) results.push(pair.key.toJSON() + ':' + value);
    });
    return '{' + results.join(',') + '}';
  }
});
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },
  toJSON: function() {
    return Hash.toJSON(this);
  }
});
Object.extend(String.prototype,{
  parseJSON: function(sanitize) {
	if (this.length == 0) return {};
    try {
      if (!sanitize || (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)))
        return eval('(' + this + ')');
    } catch (e) {}
    throw new Exception('Badly formated JSON string: ' + this);
  },
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  }
});
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});
Object.extend(Object, {
  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}
/*------------END JSON JS---------------- */


/** logo link **/
var invalidImage;
var islabelexists;
$('#header div.header_logo').click(function() {
	if (!$(this).attr('x-cms-id')) {
		window.location.href='index.php';
	}
});

/* language selectors */
// hover
$('div.language_selector li').hover(function() {$(this).addClass("over");},function() {if (!$(this).hasClass("x-stay")) $(this).removeClass("over");});
// click
$('div.language_selector li').click(function () { if ($('a',$(this)).attr("href")) { window.location.href = $('a',$(this)).attr("href");}});

/* welcome page boxes */
// hover
$('div.welcome_banner').hover(function() {$(this).addClass("over");},function() {$(this).removeClass("over");});
// click
$('div.welcome_banner').click(function () {
	if ($('a',$(this)).attr("href")) {
		window.location.href = $('a',$(this)).attr("href");
	}
});

/** news **/
$(function(){ 
   // $("div#news ul").liScroll({travelocity: 0.025});
});

/** category menu **/
// hover
$('div#category_navigation li').hover(function() {$(this).addClass("over");},function() {if (!$(this).hasClass("x-stay")) $(this).removeClass("over");});
// click
$('div#category_navigation li').click(function () { if ($('a',$(this)).attr("href")) { window.location.href = $('a',$(this)).attr("href");}});

/** page menu **/
// hover
$('div#page_navigation li').mouseover(function(e) {e.stopPropagation();$(this).addClass("over");});
$('div#page_navigation li').mouseout(function(e) {e.stopPropagation();if (!$(this).hasClass("x-stay")) $(this).removeClass("over");});
// click
$('div#page_navigation li').click(function (e) { e.stopPropagation(); if ($('a',$(this)).attr("href")) { window.location.href = $('a',$(this)).attr("href");}});

/** plugin history **/
$('ul.x-cms-history li.entry').hover(function() {$(this).addClass("over");},function() {if (!$(this).hasClass("x-stay")) $(this).removeClass("over");});
// click
$('ul.x-cms-history li.entry').click(function () { if ($('a',$(this)).attr("href")) { window.location.href = $('a',$(this)).attr("href");}});

/** frontpage selector **/
$('#market_select').change(function() {
	window.location.href=$(this).val();
});

/** print icon **/
$('a.printlink').click(function() {
	window.print();
});

/** plugin filter searching **/
$('select.x-cms-selfilter , input.x-cms-txtfilter').each(function() {
	$(this).change(function() {
		selectionFilter($(this).attr('name'),$(this).val());
	});
});
$('input.x-cms-txtfilter').keyup(function() {
	selectionFilter($(this).attr('name'),$(this).val());
});



//Move on partylabel.
$('#partylabel').change(function() {
	var $this = $(this);

	if($this.val() != "")
	{
		var partylabeval = $this.val();
		var partlablearr = partylabeval.split("_");
		//alert(partlablearr[1]);	
		if(partlablearr[1] > 0)
			window.location="http://www.partybeats.ch/index.php?partylabel="+partylabeval;
		else
			window.location="http://www.partybeats.ch/index.php";
	}
	else
		window.location="http://www.partybeats.ch/index.php";
});

$('#location').change(function() {
	var $this = $(this);
	if(eval($this.val()) > 0) {
	
			var currentHref = window.location.href;
			var redstrarr = currentHref.split("&");

			var redstr = "";
			for(x=0; x < redstrarr.length; x++)
			{
				if(redstrarr[x].search("location="))
				{
					redstr+=redstrarr[x];
				}
			}
			//console.info(redstr);
		window.location = redstr+"&location="+eval($this.val());
	}
});

$(document).ready(function(){
	$('li.panel:gt(1)').hide();
	$('#myContent').show();
	
});

//Color
$($(".hasborder")).hover(
	 function () {
		$(this).addClass("topnavbg");
		$(this).css("color","#FFFFFF");
    }, 
     function () {
		if($(this).attr('id') != "currentnav"){
		   $(this).css("color","#333333");
		}
		$(this).removeClass("topnavbg");
    }
);

var prevbackground = $("#newsletter").css("background");
$($("#newsletter")).hover(
	 function () {
		var bgcolor = navhovercolor;
		$("#newsletter").css("background-color",bgcolor);
		$("#newsletter a").css("color","#FFFFFF");
		$("#newsletter").css("background",bgcolor);
    }, 
     function () {
		var strx = window.location.href;
		if(strx.search("newsletter.php") < 0 )
		{		
			$("#newsletter").css("background-color","#ffffff");
			$("#newsletter a").css("color","#000000");
			$("#newsletter").css("background",prevbackground);
		}
    }
);

$('#album_partylable').change(function() {
	getAlbums();
});
$('#datelabel_id').change(function() {
	getAlbums();
});







$('#x-cms-voteme').click(function() {
	
	
	var votesquestions = $(".x-cms-vote-question", $("#x-cms-voting-list"));
	
	var choicesList = Array();
	for(var x= 0; x <votesquestions.length; x++ )
	{
		var p = Object.toJSON({
			'question_id': $(votesquestions[x]).attr('question-id'),
			'choices': getChildsSelected($(votesquestions[x]).attr('x-cms-vote-type'), $(votesquestions[x]).attr('question-id'))
		});

		choicesList.push(p);
	}
	voteMe(choicesList.join(","));
});

function getChildsSelected(type, question_id)
{
	var childs;
	if(type == 'single') {
		childs = $("input:radio", $('#question-choices-'+question_id));
	}
	else {
		childs = $("input:checkbox", $('#question-choices-'+question_id));
	}
	var choicarr = Array()
	for( x = 0; x < childs.length; x++) {
		if(childs[x].checked == true)
			choicarr.push($(childs[x]).val());
	}
	return choicarr.join(",");
}

$('.x-cms-vote-results').click(function() {

	var votesquestions = $(".x-cms-vote-question", $("#x-cms-voting-list"));
	for(var x= 0; x < votesquestions.length; x++ )
	{
		if(x < votesquestions.length-1) {
			$('#x-cms-show-vote-'+$(votesquestions[x]).attr('question-id')).hide();
		}

		$('#question-choices-'+$(votesquestions[x]).attr('question-id')).hide();
		$('#question-vote-result-'+$(votesquestions[x]).attr('question-id')).fadeIn(500);
	}
	$('.vote-button').hide();	
});

$('.x-cms-show-vote').click(function() {

	var votesquestions = $(".x-cms-vote-question", $("#x-cms-voting-list"));
	for(var x= 0; x <votesquestions.length; x++ )
	{
		$('#question-vote-result-'+$(votesquestions[x]).attr('question-id')).hide();
		$('#question-choices-'+$(votesquestions[x]).attr('question-id')).fadeIn(500);
	}
	$('.vote-button').show();	
});

function voteMe(choice)
{
	$.post(window.location.href, {'a': 'votes', 'choice':'['+choice+']', "action":"myvote"} , 
	function(result) {
		if(result.success) {
			for(var x= 0; x <result.votetext.length; x++ )
			{
				$('#question-choices-'+result.votetext[x].question_id).html("");
				$('#question-choices-'+result.votetext[x].question_id).hide();
				$('#question-vote-result-'+result.votetext[x].question_id).html(result.votetext[x].resultdata);
				$('#question-vote-result-'+result.votetext[x].question_id).fadeIn(500);
			}
			$('.vote-button').hide();
		}		
	},"json");
}		
function getAlbums()
{
		$.post(window.location.href, {'a': 'albums', 'date':$('#datelabel_id').val(), 'label_id':$('#album_partylable').val(), 'location':$("#album_location").val(),"action":"filteralbum"} , 
		function(result) {
			if(result.success) {
				
				if(result.admin == 'true')
				{
					$("#albums_list").html(result.albums);
					$("#album_location").html(result.locationcombo);
				}
				else 
				{
					$("#hiddenresult").html(result.albums);
					$("#album_location").html(result.locationcombo);
					initPagination();
				}
			}
		},"json");
}

function trimString(str) {
	  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

//This function is used for email validation
function isValid(str) {

	var emailFilter=/^.+@.+\..{2,3}$/;
	if (!(str.match(emailFilter))) {
		return false;
	}
	else {
		return true;
	}
}
