
System = {};
System.Data = {};
System.UI = {};
System.UI.Elements = {};
System.Extend = {};
System.UI.Windows = {};
System.Globals = {};

window.pathPrefix = "";

//windows
function msg_window(data,lang_code,setModal){
	if(typeof(lang_code) === "undefined"){lang_code = "hr"};
	if(typeof(setModal) === "undefined"){setModal = false};
	if($("#msg-holder").length < 1){
		$("body").append("<div id='msg-holder'></div>");
	}
	var buttonTextClose = getButtonText("close",lang_code);
	var buttonsVal = {};
	buttonsVal[buttonTextClose] = function() { $(this).dialog("destroy"); };
    $("#msg-holder").html(data);
	$("#msg-holder").dialog({closeOnEscape:false,modal:setModal,buttons: buttonsVal,title: "Men's locker:",minWidth: 400,width: 400});	
 }
 
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function getButtonText(buttonType,lang_code){
	var buttonLangArray = window["button_types_"+lang_code];
	var buttonText = buttonLangArray[buttonType]; 
	return buttonText;
}

function setLangVars(){
	   var urlVars = getUrlVars();
		if(typeof(urlVars.lang) !== "undefined"){
			window["lang_code"] = urlVars.lang;
		}else{
			window["lang_code"] = "hr";
	   }
}

function convertLightboxLinks(content,replaceContainer,inputAttr,outputAttr,outputAttrType){
	$("body").append("<div style='display:none' id='ReplaceContentTempLb'></div>");
	$("#ReplaceContentTempLb").html(content);
	var inputAttrTemp = "";
    $("#ReplaceContentTempLb a").each(function(){
			if(typeof($(this).attr('name') !== "undefined")){
				var inputAttrArray = $(this).attr('name').split(":");
				if(inputAttrArray.length === 1){
					inputAttrTemp = inputAttrArray.toString();
					if(inputAttrTemp === inputAttr){
						$(this).removeAttr('name');
						if(outputAttrType == "rel"){
							$(this).attr('rel',outputAttr);
						}else if(outputAttrType == "class"){
							$(this).addClass(outputAttr);
						}
					}
				}else{
					inputAttrTemp = inputAttrArray[0];
					var galleryLink = "[" + inputAttrArray[1] + "]";
					if(inputAttrTemp === inputAttr){
						$(this).removeAttr('name');
						if(outputAttrType == "rel"){
							$(this).attr('rel',outputAttr + galleryLink);
						}else if(outputAttrType == "class"){
							$(this).addClass(outputAttr);
						}
					}
				}
			}
	});
	var outputContent = $("#ReplaceContentTempLb").html();
	$("#ReplaceContentTempLb").remove();
	$(replaceContainer).html(outputContent);
}

//image dim constrain
function imageDimConstrain(jqObject,actionType,dimConstrainVal,type){
	
	//if(typeof(type) == "undefined"){type = "all"};
	
	var widthStr = /*jqObject.width();*/jqObject.css("width");
	var heightStr = /*jqObject.height();*/jqObject.css("height");
    
    if(typeof(widthStr) != "undefined"){
        var width = widthStr.split("px");
        width = parseInt(width[0]);
        var height = heightStr.split("px");
        height = parseInt(height[0]);
        
        var ratio = width / height;
        
        var newWidth = 1;
        var newHeight = 1;
        
        var oversizeRatioWidth = 1;
        var oversizeRatioHeight = 1;
        
        if(width > dimConstrainVal){
            oversizeRatioWidth = width / dimConstrainVal;
        }
        if(height > dimConstrainVal){
            oversizeRatioHeight = height / dimConstrainVal;
        }
        
        if(type === "width"){
            newWidth = Math.round(width / oversizeRatioWidth);
            newHeight = Math.round(newWidth / ratio);
        }else if(type === "height"){
            newHeight = Math.round(height / oversizeRatioHeight);
            newWidth = Math.round(newHeight * ratio);
        }else if(type === "all"){
            if(width > height){
                newWidth = Math.round(width / oversizeRatioWidth);
                newHeight = Math.round(newWidth / ratio);
            }else if(width < height){
                newHeight = Math.round(height / oversizeRatioHeight);
                newWidth = Math.round(newHeight * ratio);
            }else if(width === height){
                newWidth = Math.round(width / oversizeRatioWidth);
                newHeight = Math.round(height / oversizeRatioHeight);
            }
        }
        
        if(actionType === "return"){
            var returnVal = [];
            returnVal[0] = newWidth; 
            returnVal[1] = newHeight; 
            return returnVal;
        }else if(actionType === "change"){
            newWidth = newWidth + "px";
            newHeight = newHeight + "px";
            jqObject.css("width",newWidth);
            jqObject.css("height",newHeight);
        }
    }
}

/*function imageDimConstrain(jqObject,actionType,dimConstrainWidth,dimConstrainHeight){
	
	if(typeof(type) === "undefined"){type = "all"};
	
	var widthStr = jqObject.css("width");
	var heightStr = jqObject.css("height");
	
	var width = widthStr.split("px");
    width = parseInt(width[0]);
	var height = heightStr.split("px");
	height = parseInt(height[0]);
	
	var ratio = width / height;
	
	var newWidth = width;
	var newHeight = height;
	
	var returnVal = [];
	
	if((width > dimConstrainWidth) && (height > dimConstrainHeight)){
		if(width >= height){
			newWidth = dimConstrainWidth;
			newHeight = Math.round(newWidth / ratio);
		}else if(width <= height){
			newHeight = dimConstrainHeight;
			newWidth = Math.round(newHeight * ratio);
		}
	}else if((width > dimConstrainWidth) && (height < dimConstrainHeight)){
		newWidth = dimConstrainWidth;
		newHeight = Math.round(newWidth / ratio);
	}else if((width < dimConstrainWidth) && (height > dimConstrainHeight)){
		newHeight = dimConstrainHeight;
		newHeight = Math.round(newHeight * ratio);
	}
	
	if(actionType === "return"){
		returnVal[0] = newWidth; 
		returnVal[1] = newHeight; 
		return returnVal;
	}else if(actionType === "change"){
		newWidth = newWidth + "px";
		newHeight = newHeight + "px";
		jqObject.css("width",newWidth);
		jqObject.css("height",newHeight);
	}
}*/

function elementsCount(selector,elementType){
    var ctr = 0;
    $(selector).find("*").each(function(){
       if($(this).is(elementType)){
           ctr += 1;
       }
    });
    return ctr;
}

function elementsConstrain(selector,selectorType,args){
	//selectorType = element / container;
	//args = object / contains:  fontSizeSub[px], fontColor, fontSizeMin[px], fontSizeMax[px], imageConstrain[px], imageConstrainType - width/height/blank = all
    //var imgNum = elementsCount(selector,"img");
    var ctr = 0;
    
    if(typeof(args.fontSizeSub) == "undefined"){
        args.fontSizeSub = 0;
    }
    if(typeof(args.fontSizeMin) == "undefined" || args.fontSizeMax == "undefined"){
        args.fontSizeMin = 0;
        args.fontSIzeMax = 0;
    }
	if(typeof(args.fontColor) == "undefined"){
		args.fontColor = "";
	}
	if(typeof(args.imageConstrain) == "undefined"){
		args.imageConstrain = "";
	}
	if(typeof(args.imageConstrainType) == "undefined"){
		args.imageConstrainType = "";
	}
	
	if(selectorType === "container"){
        var containerWidth = $(selector).width();
        $(selector).find("*").each(function(){
		
			if(args.fontSizeSub > 0){
				var curFontSize = $(this).css("font-size");
                if(typeof(curFontSize) != "undefined"){
                    var curFontSizeArray = curFontSize.split("px");
                    curFontSize = curFontSizeArray[0];
                        
                    var newFontSize = curFontSize - args.fontSizeSub;
                    if(args.fontSizeMin > 0 && args.fontSizeMax > 0){
                        if(newFontSize < args.fontSizeMin){
                            newFontSize = args.fontSizeMin;
                        }else if(newFontSize > args.fontSizeMax){
                            newFontSize = args.fontSizeMax;
                        }
                    }
                    newFontSize = newFontSize + "px";
                        
                    $(this).css("font-size",newFontSize);
                }
				
			}
			
			if(args.fontColor !== ""){
				if($(this).is("p") || $(this).is("span") || $(this).is("div")){
					$(this).css("color",args.fontColor);
				}
			}
			
            if($(this).attr("class") == "videoPlayerContainer"){
                var imgObj = $(this).children(".videoPlayer").children(".videoPlayerStill");
                var imgWidth = $(this).children(".videoPlayer").css("width");
                var imgHeight = $(this).children(".videoPlayer").css("height");
                var imgSrc = imgObj.attr("src");
                var imgRel = imgObj.attr("rel");
                var imgHtml = "<a href='"+imgRel+"'><img id='videoPlayerStill"+ctr+"'  src='"+imgSrc+"'style='width:"+imgWidth+";height:"+imgHeight+";'/></a>";
                $(this).html(imgHtml);
                var newImgObj = $("#videoPlayerStill"+ctr);                
                imageDimConstrain(newImgObj,"change",args.imageConstrain,args.imageConstrainType);
                ctr++;
            }			
            
            if(args.imageConstrain !== ""){
				if($(this).is('img')){
					if(args.imageConstrainType !== ""){
						imageDimConstrain($(this),"change",args.imageConstrain,args.imageConstrainType);
					}else{
						imageDimConstrain($(this),"change",args.imageConstrain);
					}
				}
			}
		});
	}else if(selectorType === "elements"){
		$(selector).each(function(){
	
			if(args.fontSizeSub > 0){
				
				var curFontSize = $(this).css("font-size");
				var curFontSizeArray = curFontSize.split("px");
				curFontSize = curFontSizeArray[0];
					
				var newFontSize = curFontSize - args.fontSizeSub;
                    if(args.fontSizeMin > 0 && args.fontSizeMax > 0){
                    if(newFontSize < args.fontSizeMin){
                        newFontSize = args.fontSizeMin;
                    }else if(newFontSize > args.fontSizeMax){
                        newFontSize = args.fontSizeMax;
                    }
                }
					
				newFontSize = newFontSize + "px";
					
				$(this).css("font-size",newFontSize);
				
			}
			
			if(args.fontColor !== ""){
				if($(this).is("p") || $(this).is("span") || $(this).is("div")){
					$(this).css("color",args.fontColor);
				}
			}
			
			if(args.imageConstrain !== ""){
				if($(this).is('img')){
					if(args.imageConstrainType !== ""){
						imageDimConstrain($(this),"change",args.imageConstrain,args.imageConstrainType);
					}else{
						imageDimConstrain($(this),"change",args.imageConstrain);
					}
				}
			}
		});
	}
}

function elementsTextConstrain(element,args){
	// args =  cahrNum,endMark
	if(typeof(args.endMark) === "undefined"){
		args.endMark = " ...";
	}
	var charNum = args.charNum;
	var charCtr = 0;
	var curText = "";
	var limitFlag = 0;
	$(element).contents().each(function(){
		if(limitFlag !== 1){
			curText = $(this).text();
			charCtr += curText.length;
		}else{
			charCtr = 0;
			$(this).remove();
		}
		if(charCtr === charNum){
			//$(this).text(curText+args.endMark);
			limitFlag = 1;
		}else if(charCtr > charNum){
			var curTextLength = curText.length;
			var charOver = charCtr - charNum;
			var cutEnd = curTextLength - charOver;
			var returnCurText = curText.substr(0,cutEnd);
			$(this).text(returnCurText+args.endMark);
			limitFlag = 1;
		}
	});
}

/*function elementsTextConstrain(selector,args){
	// args =  charNum,endMark
    if(typeof(args.endMark) === "undefined"){
		args.endMark = " ...";
	}
	$(selector).contents().each(function(){
        alert($(this).text());
        if($(this).text().length > 1){
            $(this).text(stringConstrain($(this).text(),args.charNum,args.endMark));
        }
	});
}

function stringConstrain(inputStr,charNum,endMark){
    if(typeof(endMark) == "undefined"){
        endMark = "";
    }
    var newStr = "";
    var strLen = inputStr.length;
    if(strLen > charNum){
       var charOver = strLen - charNum;
       var cutEnd = strLen - charOver;
       newStr = inputStr.substr(0,cutEnd) + endMark;
    }else{
        newStr = inputStr;
    }
    return newStr;
}*/

function tempDataSet(tempSelector,data){
	if($(tempSelector).length === 0){
		$("body").append("<div id="+tempSelector+" style='display:none;'></div>");
	}
	tempSelector = "#"+tempSelector;
	$(tempSelector).html(data);
}

function tempDataGet(tempSelector){
	tempSelector = "#"+tempSelector;
	var returnData = $(tempSelector).html();
	return returnData;
}

//email decode
function emailDecode(selector) {
	/*selectorArray = selectorStr.split(";");
	for(i in selectorArray){
		emailStr = $(selectorArray[i]).text();
		emailArray = emailStr.split("|");
		outEmailStr = emailArray[0]+"@"+emailArray[1]+"."+emailArray[2];
		$(selectorArray[i]).text(outEmailStr);
		mailtoStr = "mailto:"+outEmailStr;
		$(selectorArray[i]).attr("href",mailtoStr);
	}*/
    emailArray = $(selector).text().split("|");
    outEmailStr = emailArray[0]+"@"+emailArray[1]+"."+emailArray[2];
    mailtoStr = "mailto:"+outEmailStr;
    $(selector).attr("href",mailtoStr);
    $(selector).text(outEmailStr);
}

//z-index fix
function zindexStackRebuild(){
    
}

//DOWNLOAD IFRAME
function downloadIframeAppend(controllerPathQuery){
    /*if(typeof(window.downloadIframeLastId) != "undefined"){
        $(window.downloadIframeLastId).remove();
    }*/
    downloadIframeRemove();
    var iframeID = "#downloadIframe"+Math.ceil(1000000*Math.random());
    //window.downloadIframeLastId = iframeID;
	$("body").append('<iframe class="downloadIframe" style="width:0px; height:0px; border: 0px" id='+'"'+iframeID+'"'+' src='+'"'+controllerPathQuery+'"'+'></iframe>');
}

function downloadIframeRemove(){
    $(".downloadIframe").remove();
}

//MENU OPERATIONS
function menuInit(menuSelector,menuSelectorPage){
       var selectorPageFull;
       var selectorPageHref;
       if(typeof(menuSelectorPage) != "undefined"){
          selectorPageFull = "#"+menuSelector+" li#"+menuSelectorPage+" span";
          $(selectorPageFull).css({"color":"red"});
       }
       $("#"+menuSelector+" li").hover(
           function(){
               $(this).children().css("color","#fafafa");
           },function(){
               $(this).children().css("color","#000000");
           }
       );
       $("#"+menuSelector+" li").click(function(){
           var link = $(this).children().attr("href");
           window.location = link;
       });
}

//MISSING FUNCTIONS
//trim

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

//str repeat

String.prototype.repeat = function( num ){
    return new Array( num + 1 ).join( this );
}

//in_array

function inArray( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}

//is_array

function isArray(input){
    return typeof(input)=='object'&&(input instanceof Array);
}

//strstr

function strstr (haystack, needle, bool) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strstr('Kevin van Zonneveld', 'van');
    // *     returns 1: 'van Zonneveld'
    // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
    // *     returns 2: 'Kevin '
    // *     example 3: strstr('name@example.com', '@');
    // *     returns 3: '@example.com'
    // *     example 4: strstr('name@example.com', '@', true);
    // *     returns 4: 'name'

    var pos = 0;

    haystack += '';
    pos = haystack.indexOf( needle );
    if (pos == -1) {
        return false;
    } else{
        if (bool){
            return haystack.substr( 0, pos );
        } else{
            return haystack.slice( pos );
        }
    }
}

//basename
function basename(path) {
	return path.replace(/\\/g,'/').replace( /.*\//, '' );
}

//dirname
function dirname(path) {
	return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
}

//rand
function rand (min, max) {
    // Returns a random number
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/rand    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // %          note 1: See the commented out code below for a version which will work with our experimental (though probably unnecessary) srand() function)
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//MISSING FUNCTIONS END


//NEW 
System.generateID = function(hash){
    if(typeof(hash) == 'undefined'){hash = false}
    var date = new Date();
    var timeEpoch = date.getTime();
    var ID = timeEpoch + (System.Data.rand(1,10000) + System.Data.rand(1,100000));
    if(hash){
        ID += '';
        ID = System.Hash.md5(ID);
    }
    return ID;
}

System.Data.rand = function(min, max){
    // Returns a random number
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/rand    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // %          note 1: See the commented out code below for a version which will work with our experimental (though probably unnecessary) srand() function)
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;} else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

System.UI.Window = function(data,args){
     if(typeof(data) == 'undefined'){data = '';}
     if(typeof(args) === "undefined"){args = {};}
     if(typeof(args.autoOpen) === "undefined"){args.autoOpen = true;}
     if( typeof(args.useSourceData) == 'undefined' ){args.useSourceData = false;}
     if( typeof(args.modal) == 'undefined' ){args.modal = false;}
     if( typeof(args.title) == 'undefined' ){args.title = System.Env.siteUrl;}
     if( typeof(args.position) == 'undefined' ){args.position = "center";}
     if( typeof(args.width) == 'undefined' ){args.width = 400;}
     if( typeof(args.minWidth) == 'undefined' ){args.minWidth = args.width;}
     if( typeof(args.showClose) == 'undefined' ){args.showClose = true;}
     if( typeof(args.isResizable) == 'undefined' ){args.isResizable = false;}
     if( typeof(args.outputType) == 'undefined' ){args.outputType = 'html';}
     this.args = args;
     var useSourceData = false;
     var buttons = {"Close": function(){$(this).dialog("destroy");$(this.windowHolderSelector).remove();}};
     if(typeof(args.buttons) != 'undefined'){
         for(var prop in args.buttons){
              buttons[prop] = args.buttons[prop];
         }
     }
     this.windowHolderId = "";
     if(typeof(this.args.windowId) == 'undefined'){
         this.windowHolderId = "UI_window_" + System.generateID();
     }else{
         this.windowHolderId = this.args.windowId;
         if(this.args.useSourceData){
             useSourceData = true;
         }
     }
     this.windowHolderSelector = "#" + this.windowHolderId;
     if(!useSourceData){
        $("body").append("<div style='display:none;' id='"+this.windowHolderId+"'></div>");
        if(this.args.outputType == 'html'){
            $(this.windowHolderSelector).html(data);
        }else if(this.args.outputType == 'text'){
            $(this.windowHolderSelector).text(data);
        }
     }else{
        $(this.windowHolderSelector).html();
     }

     this.open = function(){
         var self = this;
         var args = self.args;
         if(args.showClose === true){
              $(self.windowHolderSelector).dialog({closeOnEscape:false,resizable:args.isResizable,modal:args.modal,buttons: buttons,title:args.title,position:args.position,minWidth: args.minWidth,width:args.width});
         }else if(args.showClose === false){
              $(self.windowHolderSelector).dialog({closeOnEscape:false,resizable:args.isResizable,modal:args.modal,title:args.title,position:args.position,minWidth: args.minWidth,width:args.width});
         }
     }

     this.close = function(){
        var self = this;
        $(self.windowHolderSelector).dialog("destroy");
        $(self.windowHolderSelector).remove();
     }
     if(this.args.autoOpen){
         this.open();
     }

}

System.UI.Windows.Msg = function(data,setModal,setWidth,isResizable,showClose){
    //var instance = new System.UI.Window('',{autoOpen:false});
    if(typeof(data) == 'undefined'){data = '';}
    if( typeof(setModal) == 'undefined' ){setModal = false;}
	if( typeof(setWidth) == 'undefined' ){setWidth = 400;}
	if( typeof(showClose) == 'undefined' ){showClose = true;}
	if( typeof(isResizable) == 'undefined' ){isResizable = false;}
    
    var instance = new System.UI.Window(data,{modal:setModal,width:setWidth,showClose:showClose,isResizable:isResizable,title:"System message:"});

    this.close = function(){
        instance.close();
    }
}

System.UI.Windows.Progress = function(args){
    if(typeof(args) == 'undefined'){args = {};}
    if(typeof(args.modal) == 'undefined'){args.modal = true;}
    args.showClose = false;

    var instance = new System.UI.Window(System.UI.Elements.progressIndicator,args);

    this.close = function(){
        instance.close();
    }

}

System.objSize = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

//FIXES
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}

