﻿//Livis widget func - don't remove it
function _htTrak(a,b,c,d,e) { }
var local = {};
local.gigya = {};

//Case Studies pager
function pager(containerID,items) {

    var itemsHtml='',
        index=0,
        nextItem=null,
        prevItem=null,
        mainTmpl="<div class=Pager><table><tr><td valingh=middle><h5>View more case studies</h5></td>#{itemsHtml}</tr></table></div>",
        itemTmpl="<td><a class=PagerItem href=#{href}>#{title}</a></td>",
        seperatorTmpl="<td class=PagerDivider>&nbsp;</td>",
        activeItemTmpl="<td class=PagerActiveItem>#{title}</td>",
        prevItemTemplate="<td class=PagerArrow><a class=PagerArrow href=#{href}><</a></td>",
        prevItemTemplateActive="<td class=PagerArrowActive>&nbsp;</td>",
        nextItemTemplate="<td class=PagerArrow><a class=PagerArrow href=#{href}>></a></td>",
        nextItemTemplateActive="<td class=PagerArrowActive>&nbsp;</td>";


    items.each(function(item) {
        var isActive=window.location.href.indexOf(item.href)!= -1,
            isLast=(index==items.length-1);

        //Calculate next item
        if(isActive&&!isLast) {
            nextItem=items[index+1];
        }
        //Calculate prev item
        if(isActive&&index>0)
            prevItem=items[index-1];

        //Set prev arrow
        if(index==0) {
            if(isActive)
                itemsHtml+=prevItemTemplateActive;
        }

        //Set item template
        if(isActive) {
            itemsHtml+=activeItemTmpl.interpolate(item);
        }
        else
            itemsHtml+=itemTmpl.interpolate(item);

        itemsHtml+=seperatorTmpl;

        //Set next arrow
        if(isLast) {
            if(isActive)
                itemsHtml+=nextItemTemplateActive;
            else
                itemsHtml+=nextItemTemplate.interpolate(nextItem);
        }

        index++;
    });

    //Set prev arrow
    if(prevItem!=null)
        itemsHtml=prevItemTemplate.interpolate(prevItem)+itemsHtml;

    if($(containerID)!=null)
        $(containerID).update(mainTmpl.interpolate({ itemsHtml: itemsHtml }));
}
//Case Studies next pager
function pagerJustNext(containerID,items,text) {
    var itemsHtml='',
        index=0,
        nextItem=null,
        mainTmpl="<a class=PagerItem href=#{href}>"+text+"</a>";

    items.each(function(item) {
        var isActive=window.location.href.indexOf(item.href)!= -1,
            isLast=(index==items.length-1);

        if(isActive&&!isLast)
            nextItem=items[index+1];
        index++;
    });
    if(nextItem)
        itemsHtml+=mainTmpl.interpolate(nextItem);
    if($(containerID)!=null)
        $(containerID).update(itemsHtml);
}


function LoadMap(name,options) {
    if(!GBrowserIsCompatible()) return;
    var map=new GMap2($get(options.id));
    window[name+"_map"].apply(null,[map,options]);
}
//Load google map
function paloalto_map(map,options) {

    var text="<span style='font-size:10px'><b>Gigya Inc</b>.<br />855 El Camino Real<br>Building 4, Suite 290<br>Palo Alto, CA 94301</span>";

    var lat=new GLatLng(37.43938,-122.158804);

    map.setCenter(lat,13);

    //var ctrl = new GSmallMapControl();
    //map.addControl(ctrl, text);

    var marker=new GMarker(map.getCenter());
    GEvent.addListener(marker,"click",function() {
        marker.openInfoWindowHtml(text);
    });
    map.addOverlay(marker);
    
    //change the center to something else so we can see the marker better.
    //map.setCenter(lat,13);
    
    marker.openInfoWindowHtml(text,{ maxWidth: '150',maxHeight: '90' });
    // ,{onOpenFn:function(){alert("here")} }
    //        var iw = this._map.getInfoWindow();
    //        iw.reset(iw.getPoint(),iw.getTabs(),new GSize(150,90),null,null);

}

function telaviv_map(map,options) {

    var text="<span style='font-size:10px'><b>Gigya Inc</b>.<br />132 Begin road<br>Azrieli round tower (13 floor)<br>Tel Aviv, Israel 67021</span>";

    var lat=new GLatLng(32.074366,34.79103);

    map.setCenter(lat,13);

    //var ctrl = new GSmallMapControl();
    //map.addControl(ctrl, text);

    var marker=new GMarker(map.getCenter());
    GEvent.addListener(marker,"click",function() {
        marker.openInfoWindowHtml(text);
    });
    map.addOverlay(marker);

    marker.openInfoWindowHtml(text,{ maxWidth: '150',maxHeight: '90' });

}

function DisableCookie() {
    $('ifrCookieDis').src="DisableCookie.htm";

}

function CalcelDisableCookie() {
    document.location.replace("http://www.gigya.com/public/content/privacy.aspx");
}
function OnCookieDisable() {
    $('StartMessage').setStyle({ display: "none" });
    $('YesMessage').setStyle({ display: "inline" });
}
/****************************************************  GS User ******************************/
local.gigya.GSUser=function(user) {
    this.GSUser=null;
    this.FullName="";
    this.AvatarUrl="";
    this.Email="";
    if(user) {
        this.GSUser=user;

        //Set user full name
        if(this.GSUser.nickname.length>0)
            this.FullName=this.GSUser.nickname;
        else if(user.firstName.length>0||this.GSUser.lastName.length>0)
            this.FullName=this.GSUser.firstName+" "+this.GSUser.lastName;

        //Set user mail
        this.Email=user.email;

        //Set avatar
        if(this.GSUser.thumbnailURL!=null&&this.GSUser.thumbnailURL.length>0&&this.GSUser.thumbnailURL!="null") {
            this.AvatarUrl=this.GSUser.thumbnailURL;
            local.gigya.AvatarImage.SetAvatarImage(this.GSUser.thumbnailURL);
        }
        else if(this.GSUser.photoURL!=null&&this.GSUser.photoURL.length>0) {
            this.AvatarUrl=this.GSUser.photoURL;
            local.gigya.AvatarImage.SetAvatarImage(this.GSUser.thumbnailURL);
        }
        else
            this.AvatarUrl="http://cdn.gigya.com/site/images/bsAPI/Avatar.gif";
    }
    return this;
}
local.gigya.GSUser.SetUserName=function(id) {
    var span=$(id),
    width=130;
    if(span!=null) {
        var text=span.innerHTML;
        if(span.offsetWidth>width) {
            var i=1;
            span.innerHTML='';
            while(span.offsetWidth<(width)&&i<text.length) {
                span.innerHTML=text.substr(0,i)+'...';
                i++;
            }

            returnText=span.innerHTML;
        }
    }
}
local.gigya.GSUser.prototype=
{
    getFullName: function() {
        return this.FullName;
    },
    getAvatarUrl: function() {
        return this.AvatarUrl;
    },
    getEmail: function() {
        return this.Email;
    }
}

/**************************************************************************************************/

local.gigya.UIHelpers={

    attributeName: "UIHelper"

    ,requests: []

    ,isResponsing: false

    ,get: function() {
        var b_version=navigator.appVersion;
        if(Prototype.Browser.IE&&(b_version.toLowerCase().indexOf("msie 6.")!= -1)) {
            return;
        }
        var query=$$("*["+this.attributeName+"]");

        if(query!=undefined&&query.length>0) {

            query.each(function(elm) {
                var attr=elm.getAttribute(this.attributeName);
                if(attr!=undefined&&attr!=""&&attr!="{}") {
                    var params=eval("json="+attr);
                    if(params!=undefined&&params.fn!=undefined&&typeof (this[params.fn])=='function') {
                        params.args=[elm];
                        this.requests.push(params);
                    }
                }
            } .bind(this));


            if(this.requests.length>0&&!this.isResponsing)
                this.response();
        }
    }

    ,response: function() {

        this.isResponsing=true;
        Array.forEach(this.requests,function(req) {
            this.debug("responsing...",req.args[0]);
            this[req.fn].apply(this,req.args);
        },this);
        this.isResponsing=false;
    }

    ,debug: function(str,elm) {

        var attr=elm.getAttribute("UIDebug");

        if(attr!=undefined&&attr.toString()=='true') {
            if(Prototype.Browser.Gecko) {
                console.debug(str);
            }
            else {
                var elm;
                elm=$('TraceConsole');
                if(elm==undefined) {
                    elm=new Element('textarea');
                    elm.id='TraceConsole';
                    document.body.appendChild(elm);
                    elm.innerHTML="";
                    elm.setStyle({ 'height': '400px',width: '300px','position': 'absolute',top: 0,left: 0 });
                }

                if(Sys!=undefined)
                    Sys.Debug.trace(str);
                else
                    elm.innerHTML+=str+'\n\r -------- \n\r';
            }
        }

    }



    ,height100: function(elm) {

        var This=this;

        Event.observe(window,'resize',function(e) {
            this.debug('resizing event occuried.',elm);

            if(Prototype.Browser.IE) {
                if(elm.Height100==undefined)
                    elm.Height100={}

                clearTimeout(elm.Height100.interval);
                elm.Height100.interval=setTimeout(function() {
                    resize.apply(This,[elm]);
                },200);
            }
            else
                resize.apply(this,[elm]);

        } .bind(this));

        resize.apply(this,[$(elm)]);

        function resize(elm) {
			
            var name=(elm.id!=undefined&&elm.id!=""?elm.id:elm.className);
            this.debug("start resize element: "+name,elm);
            var Client={
                viewportWidth: function() {
                    return self.innerWidth||(document.documentElement.clientWidth||document.body.clientWidth);
                },

                viewportHeight: function() {
                    return self.innerHeight||(document.documentElement.clientHeight||document.body.clientHeight);
                },

                viewportSize: function() {
                    return { width: this.viewportWidth(),height: this.viewportHeight() };
                }
                  ,getPageSizeWithScroll: function() {
                      if(!Prototype.Browser.IE) {
                          if(window.innerHeight&&window.scrollMaxY) {// Firefox
                              yWithScroll=window.innerHeight+window.scrollMaxY;
                              xWithScroll=window.innerWidth+window.scrollMaxX;
                          } else if(document.body.scrollHeight>document.body.offsetHeight) { // all but Explorer Mac
                              yWithScroll=document.body.scrollHeight;
                              xWithScroll=document.body.scrollWidth;
                          } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
                              yWithScroll=document.body.offsetHeight;
                              xWithScroll=document.body.offsetWidth;
                          }
                          arrayPageSizeWithScroll=new Array(xWithScroll,yWithScroll);
                          return arrayPageSizeWithScroll[1];
                      }
                      else {

                          var d=document.documentElement;
                          var b=document.body;
                          var who=d.offsetHeight?d:b;
                          return Math.max(who.scrollHeight,who.offsetHeight);


                      }

                  }
            };


            try {

                if(elm.Height100==undefined) {
                    elm.Height100={};
                    elm.Height100.orgHeight=elm.getHeight();
                    elm.Height100.orgScroll=Client.getPageSizeWithScroll();
                }

                var attr=elm.getAttribute(this.attributeName);
                if(attr==undefined||attr==""||attr=="{}") {
                    this.debug(this.attributeName+" is undefined or empty.",elm);
                    return;
                }

                var params=eval("json="+attr);
                var parent=params.parentId!=undefined?$(params.parentId):elm.getOffsetParent();

                this.debug('parent : '+(parent.tagName),elm);


                this.debug('original height: '+elm.Height100.orgHeight,elm);
                this.debug('current height: '+elm.getHeight(),elm);

                normalize(elm);
                var beforResize=Client.getPageSizeWithScroll();
                this.debug('total scroll befor resize: '+beforResize,elm);

                var height=parent.getHeight();
                //                parentTopOffset = Sys.UI.DomElement.getBounds(parent).y;
                //                elmTopOffset = Sys.UI.DomElement.getBounds(elm).y;
                //                parentTopOffset = parent.cumulativeOffset().top;
                //                elmTopOffset = elm.cumulativeOffset().top;

				
                parentTopOffset=$(parent).cumulativeOffset().top;
                elmTopOffset=$(elm).cumulativeOffset().top;

                ///get rid of the top offset.
                height-=(elmTopOffset-parentTopOffset);
                this.debug('parent Offset : '+(parentTopOffset)+', elm Offset: '+elmTopOffset,elm);

                ///reduce.
                if(params.reduce!=undefined)
                    height-=params.reduce;


                ///reduce.
                if(params.reduceElement!=undefined) {

                    var redElm=$(params.reduceElement.id);
                    var elmHeight=redElm.getHeight();

                    if(params.reduceElement.maxHeight!=undefined)
                        height-=elmHeight>params.reduceElement.maxHeight?params.reduceElement.maxHeight:elmHeight;
                    else
                        height-=elmHeight;
                }

                ///increase.
                if(params.increase!=undefined)
                    height+=params.increase;


                ///set the height
                elm.setStyle({ minHeight: (height)+'px' });


                if(elm.getHeight()>height)
                    elm.setStyle({ minHeight: (height-(elm.getHeight()-height))+'px' });


                this.debug('resize height to ('+height+'): '+elm.getHeight(),elm);

                ///make sure there is no scroll that wasnt planned.
                var afterResize=Client.getPageSizeWithScroll();
                this.debug('total scroll after resize: '+afterResize,elm);


                ///Make sure we dont add scroll.
                var diffrences=afterResize-beforResize;


                this.debug('diffrences('+diffrences+'): ',elm);
                if(diffrences>0) {
                    height=(height-diffrences);
                    elm.setStyle({ minHeight: (height)+'px' });

                    if(elm.getHeight()>height)
                        elm.setStyle({ minHeight: (height-(elm.getHeight()-height))+'px' });



                    this.debug('avoiding extra scroll,resized to ('+height+'): '+elm.getHeight(),elm);
                }




                ///make sure we dont get a height that is lower than the original height of the element.
                if(params.originalHeight!=undefined
                    &&params.originalHeight==true
                    &&elm.Height100!=undefined
                    &&elm.Height100.orgHeight!=undefined
                    &&elm.Height100.orgHeight>elm.getHeight())
                // Client.getPageSizeWithScroll() > document.viewport.getHeight())
                {
                    height=elm.Height100.orgHeight;
                    //elm.setStyle({ minHeight: (height) + 'px' });
                    this.debug('size is lower than the original height ,resized to original height: '+height,elm);
                }

                this.debug('Done. ('+height+'):  '+elm.getHeight(),elm);
                this.debug('',elm);


                ///remove the height attribute.
                elm.setStyle({ height: null });
                elm.setStyle({ height: null });

            } catch(e) {
                this.debug('Exception : '+e,elm);
                try {
                    if(elm!=undefined&&elm.Height100==undefined) {
                        elm.setStyle({ minHeight: elm.Height100 });
                    }
                } catch(e) {
                    this.debug('Inner Exception : '+e,elm);
                }
            }
            function normalize(elm) {
                elm.setStyle({ height: null });elm.setStyle({ height: null });
                elm.setStyle({ minHeight: null });elm.setStyle({ minHeight: null });
            }
        }



    }

}


Event.observe(window,'load',function() {
	local.gigya.UIHelpers.get();
});



